$(document).ready(function() {
    var StBodyClass = $('body').prop('class');
    if( StBodyClass == 'index' ) {
        Init.index();
    } else {
        Init.login()
    }
});

var Init = {
    'login' : function() {
        DracoFuncs.ajaxForm('FormLogin');
    },
    'index' : function() {
        Menu.start();
        Ping.init();
        if( Configs.Action ) {
            initBasePackage(BasePackage);
        }
    }
};

var BasePackage = {
    'Usuario' : {
        'dados' : function() {
            DracoFuncs.setProperties();
            DracoFuncs.ajaxForm('FormDadosUsuario');
        },
        'trocarSenha' : function() {
            DracoFuncs.ajaxForm('FormTrocarSenha');
            DracoFuncs.PasswordMeter.init( 'ChangePass_NewPass' );
        },
        'preferencias' : function() {
            DracoFuncs.ajaxForm('FormPreferencias');
        },
        'atribuicoes' : function() {
            DracoFuncs.ToolTip.init(
                'Atri_descricao',
                'Acao',
                {'width':300, 'top':-80, 'left':-150},
                {}
            );
        },
        'relatorios' : function(isFilterInitialize){
            DracoFuncs.ToolTip.init(
                'IndRep_Avaliacao',
                'Avaliacao',
                {'width':300, 'top':-80, 'left':-150},
                {'over':'Ver Detalhes','out':'Passe o Mouse'}
            );

            $('a[id*=IndRep_AvaliacaoTip]').each(function() {
                var IDUsuario = $(this).prop('id').replace('IndRep_AvaliacaoTip', '');
                $(this).bind('click', function(e) {
                    location.href = Configs.Site.url + 'avaliacao/visualizar-avaliacao/usuario/' + IDUsuario;
                    return false;
                });
            });

            DracoFuncs.Report.Zebra.init( ['IndRep_ReportContratados'] );
            var tFilter = {Start : StringUtils.replaceAll($('#InpRep_StartDateFilter').val(), '/', '-'), End : StringUtils.replaceAll($('#InpRep_EndDateFilter').val(), '/', '-')};
            DracoFuncs.Export.changeUrl('relatorio-pessoal', tFilter);

            if( !isFilterInitialize ) {
                DracoFuncs.calendar('InpRep_StartDateFilter');
                DracoFuncs.calendar('InpRep_EndDateFilter');
                DracoFuncs.setProperties();
                DracoFuncs.ajaxForm('FormFiltrarDataRelatorioPessoal');
            }
        },
        'contraCheque' : function() {
            DracoFuncs.TableList.Configure.init(
                $('#PaymentControl_user'),
                [[0,0]],
                {
                    3:{sorter:false}
                },
                {}
            );
        }
    },
    'Administracao' : {
        'funcionarios' : function() {
            DracoFuncs.TableList.Configure.init(
                $('#FuncList_funcionarios'),
                [[0,0]],
                {
                    2:{sorter:false},
                    3:{sorter:false},
                    4:{sorter:false}
                },
                {selected:"#list-all", type:"employee"}
            );

            DracoFuncs.TableList.Filter.create('FuncList_funcionarios', 'list-all', 'administracao');
            DracoFuncs.TableList.Filter.create('FuncList_funcionarios', 'list-active', 'administracao');
        },
        'visualizarFuncionario' : function() {
            DracoFuncs.Toggle.configure('ViewUser');
        },
        'editarFuncionario' : function() {
            DracoFuncs.Toggle.configure('EditUser');
            doRequest("post", Configs.Site.url+'departamento/selectCaseSetores/', "IDDepartamento="+$('#EditUser_IDDepartamento').val()+"&IDUsuario="+$('#EditUser_IDUsuario').val(), function(response){
                $('#EditUser_IDSetor').html(response)
            })
            doRequest("post", Configs.Site.url+'funcao/selectCasePerfil/', "IDFuncao="+$('#EditUser_IDFuncao').val()+"&IDUsuario="+$('#EditUser_IDUsuario').val(), function(response){
                $('#EditUser_IDPerfil').html(response)
            })
            DracoFuncs.selectCase.init(['sector', 'profile'], 'EditUser');
            DracoFuncs.Dependent.init('EditUser');
            DracoFuncs.setProperties();
            DracoFuncs.ajaxForm('FormEditarUsuario');
            DracoFuncs.Money.priceFormat();
        },
        'cadastrarFuncionario' : function() {
            DracoFuncs.Toggle.configure('CreateEmpl');
            doRequest("post", Configs.Site.url+'departamento/selectCaseSetores/', "IDDepartamento="+$('#CreateEmpl_IDDepartamento').val(), function(response){
                $('#CreateEmpl_IDSetor').html(response)
            })
            doRequest("post", Configs.Site.url+'funcao/selectCasePerfil/', "IDFuncao="+$('#CreateEmpl_IDFuncao').val(), function(response){
                $('#CreateEmpl_IDPerfil').html(response)
            })
            DracoFuncs.selectCase.init(['sector', 'profile'], 'CreateEmpl');
            DracoFuncs.Dependent.init('CreateEmpl');
            DracoFuncs.setProperties();
            DracoFuncs.ajaxForm('FormCriarFuncionario');
            DracoFuncs.Money.priceFormat();
        },
        'folhaSalarial' : function() {
            DracoFuncs.Report.Zebra.init( ['SalarialSheet_ReportGeral', 'SalarialSheet_ReportFuncao', 'SalarialSheet_ReportDepartamento', 'SalarialSheet_ReportSetor'] );
            DracoFuncs.Report.Pagination.init('SalarialSheet');
        },
        'ultimosFuncionariosRegistrados' : function() {
            DracoFuncs.Report.Zebra.init( ['EmplReg_ReportContratados', 'EmplReg_ReportDemitidos'] );
            DracoFuncs.Report.Pagination.init('EmplReg');
        },
        'controlePagamento' : function() {
            DracoFuncs.TableList.Configure.init(
                $('#PaymentControl_user'),
                [[0,0]],
                {
                    6:{sorter:false},
                    7:{sorter:false}
                },
                {selected:"#list-pending-user", type:"employee-payment"}
            );

            DracoFuncs.TableList.Filter.create('PaymentControl_user', 'list-pending-user', 'administracao');
            DracoFuncs.TableList.Filter.create('PaymentControl_user', 'list-timely-payment-user', 'administracao');
        },
        'lancarPagamentoFuncionario' : function() {
            $('input[id*=ReleasePayment_DtDiaPagamento]').each(function() {
                DracoFuncs.calendar($(this).prop('id'));
            });
            DracoFuncs.setProperties();
            DracoFuncs.Money.priceFormat();
            DracoFuncs.ReleasePayment.init('ReleasePayment_FoSalarioLiquido', 'ReleasePayment_FoDescontos', 'ReleasePayment_GrossSalary');
            DracoFuncs.ajaxForm('FormLancarPagamentoFuncionario');
            DracoFuncs.Toggle.configure('ReleasePayment');
            showMessage( 'Para realizar a confirmação de um pagameto, você deverá deixar o pagamento vísivel para e inserir os dados necessários.' );
        }
    },
    'Comercial' : {
        'cadastrarCliente' : function() {
            DracoFuncs.setProperties();
            DracoFuncs.CustomerSessionToggle.IndividualOrEnterprise.init();
            DracoFuncs.ajaxForm('FormCadastrarCliente');
        },
        'cancelamento' : function(){
            DracoFuncs.TableList.Configure.init(
                $('#CancelledCalledList_called'),
                [[2,0]],
                {},
                {selected:"#list-cancelled-waiting-answer", type:"cancelled"}
            );
            DracoFuncs.TableList.Filter.create('CancelledCalledList_called', 'list-cancelled-waiting-answer', 'atendimento');
            DracoFuncs.TableList.Filter.create('CancelledCalledList_called', 'list-cancelled-waiting-customer', 'atendimento');
            DracoFuncs.TableList.Filter.create('CancelledCalledList_called', 'list-cancelled-closed', 'atendimento');
        },
        'relatorioInscricao' : function(){
            DracoFuncs.Report.Zebra.init( ['SubscriptionReport_Yearly', 'SubscriptionReport_Monthly', 'SubscriptionReport_Period'] );
            DracoFuncs.Report.Pagination.init('SubscriptionReport');
        },
        'relatorioCancelamento' : function(){
            DracoFuncs.Report.Zebra.init( ['CancelledReport_Yearly', 'CancelledReport_Monthly', 'CancelledReport_Period'] );
            DracoFuncs.Report.Pagination.init('CancelledReport');
        }
    },
    'Atendimento' : {
        'cadastrarChamadoTelefonico' : function() {
            DracoFuncs.CustomerSessionToggle.CustomerIndentifier.init();
            DracoFuncs.ajaxForm('FormCriarChamadoTelefonico');
        },
        'listarChamadoTelefonico' : function() {
            DracoFuncs.TableList.Configure.init(
                $('#PhoneCalledList_called'),
                [[2,0]],
                {5:{sorter:false}},
                {selected:"#list-phone-sector", type:"phone"}
            );

            DracoFuncs.TableList.Filter.create('PhoneCalledList_called', 'list-phone-sector', 'atendimento');
            DracoFuncs.TableList.Filter.create('PhoneCalledList_called', 'list-phone-all', 'atendimento');
            DracoFuncs.TableList.Filter.create('PhoneCalledList_called', 'list-myPhoneCalled', 'atendimento');
            DracoFuncs.TableList.Filter.create('PhoneCalledList_called', 'list-last20', 'atendimento');
        },
        'buscarChamado' : function() {
            DracoFuncs.Toggle.configure('CalledSearch');
            DracoFuncs.setProperties();
            $('form[name=FormBuscarChamado]').bind('submit', DracoSubmit.BuscarChamado.validate);

            if( !Configs.Messages.feedback ) {
                showMessage("Efetui uma busca por ID ou Avançada. Na Busca Avançada você pode escolher qualquer um dos filtros (Exceto o Id), os filtros não utilizados serão desconsiderados. Marque se a busca deve obedecer a todas as condições ou não.");
            } else {
                showError( {'StMessage' : Configs.Messages.feedback} );
            }
        },
        'resultadoBusca' : function() {
            DracoFuncs.TableList.Configure.init(
                $('#Result_called'),
                [[1,0]],
                {
                    0:{sorter:false},
                    8:{sorter:false}
                },
                {}
            );
        },
        'listarChamadoExterno' : function() {
            DracoFuncs.TableList.Configure.init(
                $('#ExternalCalledList_called'),
                [[1,0]],
                {
                    0:{sorter:false},
                    6:{sorter:false}
                },
                {selected:"#list-external-sector",type:"external"}
            );

            DracoFuncs.TableList.Filter.create('ExternalCalledList_called', 'list-external-sector', 'atendimento');
            DracoFuncs.TableList.Filter.create('ExternalCalledList_called', 'list-external-priority', 'atendimento');
            DracoFuncs.TableList.Filter.create('ExternalCalledList_called', 'list-myExternalCalled', 'atendimento');
            DracoFuncs.TableList.Filter.create('ExternalCalledList_called', 'list-myExternalCalledWaitingCustomer', 'atendimento');
        },
        'visualizarChamado' : function() {
            DracoFuncs.Toggle.Message.init('Called_Message');
            DracoFuncs.ajaxForm('FormCriarMensagem');
            DracoFuncs.selectCase.init(['sector'], 'Called');

            DracoFuncs.Called.Priority.init();
            DracoFuncs.Called.Close.init();
            DracoFuncs.Called.Faved.init();
            DracoFuncs.Called.ChangeSector.init();
            DracoFuncs.Called.ChangeResponsible.init();

            if( exists($('#' + DracoFuncs.selectCase.StPrefix + '_IDDepartamento')) ) {
                doRequest("post", Configs.Site.url+'departamento/selectCaseSetores/', "IDDepartamento="+$('#Called_IDDepartamento').val()+'&IDSetor='+$('#Called_IDSetorChamado').val(), function(response){
                    $('#Called_IDSetor').html(response)
                })
            }
        },
        'listarChamadoInterno' : function() {
            DracoFuncs.TableList.Configure.init(
                $('#InternalCalledList_called'),
                [[1,0]],
                {
                    0:{sorter:false},
                    6:{sorter:false}
                },
                {selected:"#list-internal-sector",type:"internal"}
            );

            DracoFuncs.TableList.Filter.create('InternalCalledList_called', 'list-internal-sector', 'atendimento', 'visualizar-chamado');
            DracoFuncs.TableList.Filter.create('InternalCalledList_called', 'list-internal-all', 'atendimento', 'visualizar-chamado');
            DracoFuncs.TableList.Filter.create('InternalCalledList_called', 'list-internal-customer', 'atendimento', 'visualizar-chamado');

        },
        'cadastrarChamadoInterno' : function() {
            DracoFuncs.ajaxForm('FormCriarChamadoInterno');
        },
        'relatorioIndividual' : function(isFilterInitialize) {
            DracoFuncs.ToolTip.init(
                'IndRep_Avaliacao',
                'Avaliacao',
                {'width':300, 'top':-80, 'left':-150},
                {'over':'Ver Detalhes','out':'Passe o Mouse'}
            );
            $('a[id*=IndRep_AvaliacaoTip]').each(function() {
                var IDUsuario = $(this).prop('id').replace('IndRep_AvaliacaoTip', '');
                $(this).bind('click', function(e) {
                    location.href = Configs.Site.url + 'avaliacao/visualizar-avaliacao/usuario/' + IDUsuario;
                    return false;
                });
            });
            DracoFuncs.Report.Zebra.init( ['IndRep_ReportContratados'] );
            var tFilter = {Start : StringUtils.replaceAll($('#InpRep_StartDateFilter').val(), '/', '-'), End : StringUtils.replaceAll($('#InpRep_EndDateFilter').val(), '/', '-')};
            DracoFuncs.Export.changeUrl('relatorio-individual', tFilter);
            if( !isFilterInitialize ) {
                DracoFuncs.calendar('InpRep_StartDateFilter');
                DracoFuncs.calendar('InpRep_EndDateFilter');
                DracoFuncs.setProperties();
                DracoFuncs.ajaxForm('FormFiltrarDataRelatorioIndividual');
            }
        },
        'relatorioPorSetor' : function(isFilterInitialize) {
            DracoFuncs.ToolTip.init(
                'SecRep_Avaliacao',
                'Avaliacao',
                {'width':300, 'top':-80, 'left':-150},
                {'over':'Ver Detalhes','out':'Passe o Mouse'}
            );
            $('a[id*=SecRep_AvaliacaoTip]').each(function() {
                var IDUsuario = $(this).prop('id').replace('SecRep_AvaliacaoTip', '');
                $(this).bind('click', function(e) {
                    location.href = Configs.Site.url + 'avaliacao/visualizar-avaliacao/setor/' + IDUsuario;
                    return false;
                });
            });
            DracoFuncs.Report.Zebra.init( ['SecRep_Report'] );
            var tFilter = {Start : StringUtils.replaceAll($('#SecRep_StartDateFilter').val(), '/', '-'), End : StringUtils.replaceAll($('#SecRep_EndDateFilter').val(), '/', '-')};
            DracoFuncs.Export.changeUrl('relatorio-setor', tFilter);
            if( !isFilterInitialize ) {
                DracoFuncs.calendar('SecRep_StartDateFilter');
                DracoFuncs.calendar('SecRep_EndDateFilter');
                DracoFuncs.setProperties();
                DracoFuncs.ajaxForm('FormFiltrarDataRelatorioSetor');
            }
        },
        'relatorioPorDepartamento' : function(isFilterInitialize) {
            DracoFuncs.ToolTip.init(
                'DepRep_Avaliacao',
                'Avaliacao',
                {'width':300, 'top':-80, 'left':-150},
                {'over':'Ver Detalhes','out':'Passe o Mouse'}
            );
            $('a[id*=DepRep_AvaliacaoTip]').each(function() {
                var IDUsuario = $(this).prop('id').replace('DepRep_AvaliacaoTip', '');
                $(this).bind('click', function(e) {
                    location.href = Configs.Site.url + "avaliacao/visualizar-avaliacao/departamento/" + IDUsuario;
                    return false;
                });
            });
            DracoFuncs.Report.Zebra.init( ['DepRep_Report'] );
            if( !isFilterInitialize ) {
                DracoFuncs.calendar('DepRep_StartDateFilter');
                DracoFuncs.calendar('DepRep_EndDateFilter');
                DracoFuncs.setProperties();
                DracoFuncs.ajaxForm('FormFiltrarDataRelatorioDepartamento');
            }
        }
    },
    'Departamento' : {
        'listarDepartamentos' : function() {
            DracoFuncs.TableList.Configure.init(
            $('#DepartamentList_departament'),
            [[0,0]],
            {
                2:{sorter:false},
                3:{sorter:false},
                4:{sorter:false}
            }
        );
        },
        'cadastrarDepartamento' : function() {
            DracoFuncs.ajaxForm('FormCriarDepartamento');
        },
        'editarDepartamento' : function() {
            DracoFuncs.ajaxForm('FormEditarDepartamento');
        },
        'excluirDepartamento' : function() {
            DracoFuncs.ajaxForm('FormExcluirDepartamento');
        }
    },
    'Setor' : {
        'listarSetores' : function() {
            DracoFuncs.TableList.Configure.init(
            $('#SectorList_sectors'),
            [[0,0]],
            {
                3:{sorter:false},
                4:{sorter:false},
                5:{sorter:false}
            }
        );
        },
        'cadastrarSetor' : function() {
            DracoFuncs.ajaxForm('FormCriarSetor');
        },
        'editarSetor' : function() {
            DracoFuncs.ajaxForm('FormEditarSetor');
        },
        'excluirSetor' : function() {
            DracoFuncs.ajaxForm('FormExcluirSetor');
        }
    },
    'Funcao' : {
        'listarFuncoes' : function() {
            DracoFuncs.TableList.Configure.init(
                $('#PositionList_positions'),
                [[0,0]],
                {
                    3:{sorter:false},
                    4:{sorter:false},
                    5:{sorter:false}
                }
            );
        },
        'cadastrarFuncao' : function() {
            DracoFuncs.ajaxForm('FormCriarFuncao');
        },
        'editarFuncao' : function() {
            DracoFuncs.ajaxForm('FormEditarFuncao');
        },
        'excluirFuncao' : function() {
            DracoFuncs.ajaxForm('FormDeleteFuncao');
        }
    },
    'Perfil' : {
        'listarPerfis' : function() {
            DracoFuncs.TableList.Configure.init(
                $('#ProfileList_profiles'),
                [[0,0]],
                {
                    2:{sorter:false},
                    3:{sorter:false},
                    4:{sorter:false}
                }
            );
        },
        'cadastrarPerfil' : function() {
            DracoFuncs.ajaxForm('FormCriarPerfil');
        },
        'editarPerfil' : function() {
            DracoFuncs.ajaxForm('FormEditarPerfil');
        },
        'excluirPerfil' : function() {
            DracoFuncs.ajaxForm('FormDeletePerfil');
        }
    },
    'Cliente' : {
        'buscarCliente' : function() {
            $('form[name=FormBuscarCliente]').bind('submit', DracoSubmit.BuscarCliente.validate);
            DracoFuncs.Toggle.configure('CustomerSearch');
            if( !Configs.Messages.feedback ) {
                showMessage("Efetui uma busca por ID, Documento ou Avançada. Na Busca Avançada você pode escolher qualquer um dos filtros (Exceto o Id e Documento), os filtros não utilizados serão desconsiderados. Marque se a busca deve obedecer a todas as condições ou não.");
            } else {
                showError( {'StMessage' : Configs.Messages.feedback} );
            }
        },
        'resultadoBuscaCliente' : function() {
            DracoFuncs.TableList.Configure.init(
                $('#Result_customer'),
                [[0,0]],
                {6:{sorter:false}}
            );
        },
        'visualizarCliente' : function() {
            DracoFuncs.Tabs.init();
        },
        'relatorioFinanceiro' : function() {
            DracoFuncs.Report.Zebra.init( ['FinancialReport_ReportPagamento', 'FinancialReport_ReportTipoPagamento', 'FinancialReport_ReportHistory'] );
            DracoFuncs.Report.Pagination.init('FinancialReport');
        },
        'editarCliente' :function(){
            DracoFuncs.setProperties();
            DracoFuncs.ajaxForm('FormEditarCliente');
        },
        'relatorioAtendimento' : function() {
            DracoFuncs.Report.Zebra.init( ['TreatmentReport_ReportMoreOpenedCalled', 'TreatmentReport_ReportMorePhoneCalled', 'TreatmentReport_ReportMorePhoneCalled', 'TreatmentReport_ReportMoreClosedCalled'] );
            DracoFuncs.Report.Pagination.init('TreatmentReport');
        },
        'relatorioSatisfacao' : function() {
            DracoFuncs.Report.Zebra.init( ['SatisfactionReport_ReportSatisfaction', 'SatisfactionReport_ReportEvaluation', 'SatisfactionReport_ReportGreat','SatisfactionReport_ReportVeryGood','SatisfactionReport_ReportRegular', 'SatisfactionReport_ReportBad'] );
            DracoFuncs.Report.Pagination.init('SatisfactionReport');
        },
        'relatorioComunicados' : function() {
            DracoFuncs.Report.Zebra.init( ['AnnouncementReport_ReportMoreAnnouncement', 'AnnouncementReport_ReportMoreCompliment', 'AnnouncementReport_ReportMoreCompliment', 'AnnouncementReport_ReportMoreSuggestion'] );
            DracoFuncs.Report.Pagination.init('AnnouncementReport');
        }
    },
    'Financeiro' : {
        'lancarPagamento' : function() {
            DracoFuncs.TableList.Configure.init(
                $('#ReleasePayment_customer'),
                [[0,0]],
                {5:{sorter:false},6:{sorter:false}},
                {selected:'#list-delinquent', type:'historySituation'}
            );

            DracoFuncs.TableList.Filter.create('ReleasePayment_customer', 'list-delinquent', 'financeiro');
            DracoFuncs.TableList.Filter.create('ReleasePayment_customer', 'list-delay', 'financeiro');
            DracoFuncs.TableList.Filter.create('ReleasePayment_customer', 'list-prefreeze', 'financeiro');
            DracoFuncs.TableList.Filter.create('ReleasePayment_customer', 'list-freeze', 'financeiro');
        },
        'inadimplencia' : function() {
            DracoFuncs.TableList.Configure.init(
                $('#ReleasePayment_customer'),
                [[0,0]],
                {5:{sorter:false},6:{sorter:false}},
                {selected:'#list-delinquent', type:'historySituation'}
            );

            DracoFuncs.TableList.Filter.create('ReleasePayment_customer', 'list-delinquent', 'financeiro');
            DracoFuncs.TableList.Filter.create('ReleasePayment_customer', 'list-delay', 'financeiro');
            DracoFuncs.TableList.Filter.create('ReleasePayment_customer', 'list-prefreeze', 'financeiro');
            DracoFuncs.TableList.Filter.create('ReleasePayment_customer', 'list-freeze', 'financeiro');
        },
        'estornar' : function() {
            DracoFuncs.TableList.Configure.init(
                $('#ReverseList_customer'),
                [[0,0]],
                {5:{sorter:false},6:{sorter:false}}
            );
        },
        'estornarCliente' : function() {
            DracoFuncs.Money.priceFormat();
            DracoFuncs.calendar('Reverse_DtData');
            DracoFuncs.ajaxForm('FormEstorno');
        },
        'lancarPagamentoCliente' : function() {
            $('input[id*=ReleasePayment_DtData]').each(function() {
                DracoFuncs.calendar($(this).prop('id'));
            })
            DracoFuncs.Money.priceFormat();
            DracoFuncs.setProperties();
            DracoFuncs.ajaxForm('FormLancarPagamento');
            DracoFuncs.Toggle.configure('ReleasePayment');
            showMessage( 'Para realizar a confirmação de um pagameto, você deverá deixar o pagamento vísivel para e inserir os dados necessários.' );
        },
        'relatorioInadimplentes' : function() {
            DracoFuncs.Report.Zebra.init( ['DelinquentReport_ReportLider', 'DelinquentReport_ReportGeral', 'DelinquentReport_ReportIndividual', 'DelinquentReport_ReportCancelled'] );
            DracoFuncs.Report.Pagination.init('DelinquentReport');
        },
        'relatorioPagamentos' : function() {
            DracoFuncs.Report.Zebra.init( ['PaymentReport_ReportTempo', 'PaymentReport_ReportInvestido', 'PaymentReport_ReportPontual'] );
            DracoFuncs.Report.Pagination.init('PaymentReport');
        },
        'editarDadosFinanceiro' : function() {
            DracoFuncs.setProperties();
            DracoFuncs.ajaxForm('FormEditarDadosFinanceiro');
        },
        'listarClientes' : function() {
            DracoFuncs.TableList.Configure.init(
                $('#EditFinancialList_customer'),
                [[0,0]],
                {5:{sorter:false},6:{sorter:false}}
            );
        }
    },
    'Planos' : {
        'editarPlano' : function(){
            DracoFuncs.Money.priceFormat();
            DracoFuncs.ajaxForm('FormEditarPlano');
        },
        'cadastrarPlanos' : function(){
            DracoFuncs.Money.priceFormat();
            DracoFuncs.ajaxForm('FormCadastrarPlano');
        },
        'listarPlanos' : function(){
            DracoFuncs.TableList.Configure.init(
                $('#PlanosList_plan'),
                [[0,0]],
                {
                    4:{sorter:false},
                    5:{sorter:false}
                },
                {}
            );
            DracoFuncs.Plans.init();
        }
    },
    'Avaliacao' : {
        'listarAvaliacoes' : function() {
            DracoFuncs.TableList.Configure.init(
                $('#EvaluationView_evaluation'),
                [[0,0]],
                {
                    6:{sorter:false}
                },
                {selected:"#list-evaluation-user",type:"evaluation"}
            );
            DracoFuncs.TableList.Filter.create('EvaluationView_evaluation', 'list-evaluation-user', 'avaliacao', 'visualizar-avaliacao');
            DracoFuncs.TableList.Filter.create('EvaluationView_evaluation', 'list-evaluation-sector', 'avaliacao', 'visualizar-avaliacao');
            DracoFuncs.TableList.Filter.create('EvaluationView_evaluation', 'list-evaluation-departament', 'avaliacao', 'visualizar-avaliacao');
        },
        'visualizarAvaliacao' : function() {
            DracoFuncs.Toggle.Message.init('EvaluationView_Message');
        }
    },
    'Comunicado' : {
        'listarComunicados' : function() {
            DracoFuncs.TableList.Configure.init(
                $('#AnnouncementList_annoncement'),
                [[0,0]],
                {
                    3:{sorter:false}
                },
                {selected:"#list-evaluation-user",type:"evaluation"}
            );
        }
    },
    'Boleto': {
        'listarPendencias' : function(){
            DracoFuncs.TableList.Configure.init(
                $('#ReleasePayment_billet'),
                [[0,0]],
                {
                    3:{sorter:false}
                },
                {}
            );
        },
        'listarClientes' : function(){
            DracoFuncs.TableList.Configure.init(
                $('#ReleasePayment_customer'),
                [[0,0]],
                {
                    3:{sorter:false}
                },
                {}
            );
        }
    },
    'Mensagem' : {
        'respostasParaLiberar' : function() {
            DracoFuncs.TableList.Configure.init(
                $('#BlockedMessages_blocked'),
                [[0,0]],
                {
                    3:{sorter:false},
                    4:{sorter:false}
                },
                {}
            );
        },
        'mensagemBloqueada' : function() {
            DracoFuncs.LiberationMessage.blockMessage();
            DracoFuncs.LiberationMessage.unblockMessage();
        }
    },
    'Ferramenta' : {
        'aniversariantes' : function() {
            DracoFuncs.TableList.Configure.init(
                $('#BirthdaysList_users'),
                [],
                {},
                {}
            );
        },
        'listarAvisos' : function() {
            DracoFuncs.TableList.Configure.init(
                $('#NoticesList_notices'),
                [],
                {
                    4:{sorter:false}
                },
                {}
            );
        },
        'listarAnotacoes' : function() {
            DracoFuncs.TableList.Configure.init(
                $('#NoteList_note'),
                [],
                {
                    1:{sorter:false},
                    2:{sorter:false},
                    3:{sorter:false}
                },
                {}
            );
            $('a[id*=NoteList_delete]').each(function() {
                var IDAnotacao = $(this).prop('id').replace('NoteList_delete', '');
                $(this).bind('click', function() {
                    if( confirm('Você tem certeza que deseja excluir esta anotação?') ) {
                        doRequest('post', Configs.Site.url + 'anotacao/deletar', 'IDAnotacao='+IDAnotacao, DracoSubmit.tSuccess);
                        redirectIn(location.href, 1500);
                    }
                    return false;
                })
            });
        },
        'listarChamadosPreferidos' : function() {
            DracoFuncs.TableList.Configure.init(
                $('#PreferredCalled_called'),
                [],
                {
                    4:{sorter:false}
                },
                {}
            );
        },
        'listarPerguntas' : function() {
            DracoFuncs.TableList.Configure.init(
                $('#QuestionList_question'),
                [],
                {
                    2:{sorter:false}
                },
                {}
            );
        }
    },
    'Aviso' : {
        'listar' : function() {
            DracoFuncs.TableList.Configure.init(
                $('#NoticesList_notices'),
                [],
                {
                    4:{sorter:false},
                    5:{sorter:false}
                },
                {selected:"#list-active", type:"aviso"}
            );

            DracoFuncs.TableList.Filter.create('NoticesList_notices', 'list-active', 'aviso');
            DracoFuncs.TableList.Filter.create('NoticesList_notices', 'list-future', 'aviso');
            DracoFuncs.TableList.Filter.create('NoticesList_notices', 'list-past', 'aviso');
        },
        'cadastrar' : function() {
            DracoFuncs.setProperties();
            $('.Date').each(function() {
                DracoFuncs.calendar( $(this).prop('id') );
            });
            DracoFuncs.ajaxForm('FormCriarAviso');
        },
        'editar' : function() {
            DracoFuncs.setProperties();
            $('.Date').each(function() {
                DracoFuncs.calendar( $(this).prop('id') );
            });
            DracoFuncs.ajaxForm('FormEditarAviso');
        }
    },
    'Anotacao' : {
        'cadastrar' : function() {
            DracoFuncs.ajaxForm('FormCriarAnotacao');
        },
        'editar' : function() {
            DracoFuncs.ajaxForm('FormEditarAnotacao');
        }
    },
    'Faq' : {
        'listarPerguntas' : function() {
            DracoFuncs.TableList.Configure.init(
                $('#QuestionList_question'),
                [],
                {
                    2:{sorter:false},
                    3:{sorter:false},
                    4:{sorter:false}
                },
                {}
            );

            $('a[id*=QuestionList_delete]').each(function() {
                var IDFaq = $(this).prop('id').replace('QuestionList_delete', '');
                $(this).bind('click', function() {
                    if( confirm('Você tem certeza que deseja excluir esta pergunta?') ) {
                        doRequest('post', Configs.Site.url + 'faq/deletar', 'IDFaq='+IDFaq, DracoSubmit.tSuccess);
                        redirectIn(location.href, 1500);
                    }
                    return false;
                })
            });

        },
        'cadastrar' : function() {
            DracoFuncs.ajaxForm('FormCriarPergunta');
        },
        'editar' : function() {
            DracoFuncs.ajaxForm('FormEditarPergunta');
        }
    }
};

var DracoSubmit = {
    'Params' : '',
    'setUp' : function() {
        DracoFuncs.Params = "";
        hideError();
    },
    'submit' : function(tFormSubmit) {
        if( tFormSubmit.submit ) {
            return tFormSubmit.submit.call();
        }
        DracoSubmit.setUp();
        if ( !tFormSubmit.validate() ) {
            return false;
        }
        DracoSubmit.send(tFormSubmit);
        return true;
    },
    'send' : function(tFormSubmit) {
        var tCallback = tFormSubmit.tSuccess == undefined ? DracoSubmit.tSuccess : tFormSubmit.tSuccess;
        doRequest('POST', Configs.Site.url+tFormSubmit.controllerActionSubmit, DracoSubmit.Params, tCallback);
        if( tFormSubmit.toRedirect ) {
            redirectIn(Configs.Site.url + tFormSubmit.toRedirect, 1500);
        }
    },
    'tSuccess' : function(tResponse) {
        var tResultado = eval('('+tResponse+')');
        if( tResultado.Type == 'success' ) {
            showSuccess(tResultado)
        } else {
            showError(tResultado);
        }
    },
    'Login' : {
        'submit' : function() {
            DracoSubmit.setUp();
            if ( !DracoSubmit.Login.validate() ) {
                return false;
            }
            DracoSubmit.Login.send();
            return true;
        },
        'validate' : function() {
            if( empty($('#Log_User')) ) {
                return showErrorValidate($('#Log_User'), 'Usuario');
            } else if ( empty($('#Log_Pass')) ) {
                return showErrorValidate($('#Log_Pass'), 'Senha');
            }
            DracoSubmit.Params = 'StNome='+$('#Log_User').val()+'&StSenha='+$('#Log_Pass').val();
            return true;
        },
        'send' : function() {
            var tSuccess = function(tResponse) {
                var tResultado = eval('('+tResponse+')');
                if( tResultado.Type == 'success' ) {
                    redirect(Configs.Site.url);
                } else {
                    showError(tResultado);
                }
            }
            doRequest('POST', Configs.Site.url+'login/logar', DracoSubmit.Params, tSuccess);
        }
    },
    'DadosUsuario' : {
        'controllerActionSubmit' : 'usuario/editarDados',
        'validate' : function() {
            if( !isValidForm(['EditData_ItRamal', 'EditData_StComplemento'] , $('input[type=text][id*=EditData_]')) ) {
                return false;
            }

            DracoSubmit.Params = 'StNome='+$('#EditData_StNome').val()+'&DtNascimento='+$('#EditData_DtNascimento').val()+'&StCpf='+$('#EditData_StCpf').val()+'&StRg='+$('#EditData_StRg').val();
            DracoSubmit.Params += '&StEndereco='+$('#EditData_StEndereco').val()+'&StNumero='+$('#EditData_StNumero').val()+'&StComplemento='+$('#EditData_StComplemento').val()+'&StBairro='+$('#EditData_StBairro').val();
            DracoSubmit.Params += '&StCidade='+$('#EditData_StCidade').val()+'&StEstado='+$('#EditData_StEstado').val()+'&StCep='+$('#EditData_StCep').val()+'&StEmail='+$('#EditData_StEmail').val();
            DracoSubmit.Params += '&ItRamal='+$('#EditData_ItRamal').val()+'&StDDDTelefone='+$('#EditData_StDDDTelefone').val()+'&StTelefone='+$('#EditData_StTelefone').val()+'&StDDDCelular='+$('#EditData_StDDDCelular').val();
            DracoSubmit.Params += '&StCelular='+$('#EditData_StCelular').val();
            return true;
        }
    },
    'TrocarSenha' : {
        'controllerActionSubmit' : 'usuario/editar-senha',
        'validate' : function() {
            if( !isValidForm(false , $('input[type=password][id*=ChangePass_]')) ) {
                return false;
            } else if ( DracoFuncs.PasswordMeter.points < 60 ) {
                return showError( {
                    StMessage:'Senha fraca de mais. Consiga pelo menos 60% de avaliação de segurança.'
                } );
            } else if( $('#ChangePass_NewPass').val() != $('#ChangePass_Confirm').val() ) {
                return showError( {
                    StMessage:'A confirmação não bate com a senha digitada e avaliada.'
                } );
            }
            DracoSubmit.Params = 'StSenhaAntiga='+$('#ChangePass_OldPass').val()+'&StNovaSenha='+$('#ChangePass_NewPass').val()+'&StConfirmacao='+$('#ChangePass_Confirm').val();
            return true;
        }
    },
    'Preferencias' : {
        'controllerActionSubmit' : 'usuario/editar-preferencias',
        'validate' : function() {
            if( empty($('#PrefUser_NumeroFerramentas')) ) {
                return showErrorValidate($('#PrefUser_NumeroFerramentas'), 'N&uacute;mero Ferramentas');
            }
            var ArIDFerramentas = [];
            $('input[type=checkbox][name=Preferencias]:checked').each(function() {
                ArIDFerramentas.push( $(this).val() );
            });
            if( $('#PrefUser_NumeroFerramentas').val() < ArIDFerramentas.length ) {
                return showError({
                    'StMessage':'Voc&ecirc; selecionou mais ferramentas do que o limite estipulado.'
                });
            }
            DracoSubmit.Params = 'ItMaximoFerramentas='+$('#PrefUser_NumeroFerramentas').val()+'&IDFerramentas='+ArIDFerramentas.join(', ');
            return true;
        }
    },
    'EditarUsuario' : {
        'controllerActionSubmit' : 'administracao/atualizar-funcionario',
        'validate' : function() {
            if( !isValidForm(['EditUser_ItRamal', 'EditUser_DtDemissao', 'EditUser_StComplemento'] , $('input[type=text][id*=EditUser_], select[id*=EditUser_]')) ) {
                return false;
            }
            $('#EditUser_Dados > section > .inp_txt > input').each(function() {
                DracoSubmit.Params += 'Pessoal['+$(this).prop('name')+']='+$(this).val()+'&';
            });
            $('#EditUser_Emprego > .inp_txt > input, #EditUser_Emprego > .inp_txt > select').each(function() {
                var StParameterValue = $(this).prop('class') != 'price' ? $(this).val() : DracoFuncs.Money.toDouble($(this).val());
                DracoSubmit.Params += 'Administrativo['+$(this).prop('name')+']='+StParameterValue+'&';
            });
            var IDParentesco;
            $('section[id*=Parentesco]').each(function() {
                IDParentesco = $(this).prop('id').replace('Parentesco', '');
                DracoSubmit.Params += 'Dependente['+IDParentesco+'][StNomeDependente]='+$('.inp_txt > input[name*=StNomeDependente]', this).val()+'&Dependente['+IDParentesco+'][DtNascimentoDependente]='+$('.inp_txt > input[name*=DtNascimentoDependente]', this).val()+'&Dependente['+IDParentesco+'][StGrauParentesco]='+$('.inp_txt > input[name*=StGrauParentesco]', this).val()+'&';
            });
            $('#EditUser_Setor > .inp_txt > select').each(function() {
                DracoSubmit.Params += 'Funcao['+$(this).prop('name')+']='+$(this).val()+'&';
            });
            DracoSubmit.Params += 'IDUsuario='+$('#EditUser_IDUsuario').val();
            return true;
        }
    },
    'CriarFuncionario' : {
        'controllerActionSubmit' : 'administracao/inserir-funcionario',
        'validate' : function() {
            if( !isValidForm(['CreateEmpl_StComplemento', 'CreateEmpl_ItRamal'] , $('input[type=text][id*=CreateEmpl_], select[id*=CreateEmpl_]')) ) {
                return false;
            }
            $('#CreateEmpl_Dados > section > .inp_txt > input').each(function() {
                DracoSubmit.Params += 'Pessoal['+$(this).prop('name')+']='+$(this).val()+'&';
            });
            $('#CreateEmpl_Emprego > .inp_txt > input, #CreateEmpl_Emprego > .inp_txt > select').each(function() {
                var StParameterValue = $(this).prop('class') != 'price' ? $(this).val() : DracoFuncs.Money.toDouble($(this).val());
                DracoSubmit.Params += 'Administrativo['+$(this).prop('name')+']='+StParameterValue+'&';
            });
            var IDParentesco;
            $('section[id*=Parentesco]').each(function() {
                IDParentesco = $(this).prop('id').replace('Parentesco', '');
                DracoSubmit.Params += 'Dependente['+IDParentesco+'][StNomeDependente]='+$('.inp_txt > input[name*=StNomeDependente]', this).val()+'&Dependente['+IDParentesco+'][DtNascimentoDependente]='+$('.inp_txt > input[name*=DtNascimentoDependente]', this).val()+'&Dependente['+IDParentesco+'][StGrauParentesco]='+$('.inp_txt > input[name*=StGrauParentesco]', this).val()+'&';
            });
            $('#CreateEmpl_Setor > .inp_txt > select').each(function() {
                DracoSubmit.Params += 'Funcao['+$(this).prop('name')+']='+$(this).val()+'&';
            });
            $('#CreateEmpl_Preferencias > .inp_txt > input').each(function() {
                DracoSubmit.Params += 'Preferencias['+$(this).prop('name')+']='+$(this).val()+'&';
            });
            var ArIDFerramentas = [];
            $('#CreateEmpl_Ferramentas > .inp_txt > :checked').each(function() {
                ArIDFerramentas.push( $(this).val() );
            });
            DracoSubmit.Params += 'IDFerramentas='+ArIDFerramentas.join(', ');
            return true;
        }
    },
    'CadastrarCliente' : {
        'controllerActionSubmit' : 'cliente/inserir',
        'validate' : function() {
            var toValidate = '#CreateCustomer_Individual > .inp_txt > input, #CreateCustomer_Contact > .inp_txt > input, #CreateCustomer_Financial > .inp_txt > input[type=text], select, input[name=EnTipoPagamento]:checked, input[name=EnPeriodicidade]:checked'
            toValidate += $('input[name=EnTipoCliente]:checked').val() == 'JURIDICA' ? ', #CreateCustomer_Enterprise > .inp_txt > input' : '';
            if( !isValidForm(['CreateCustomer_StComplemento', 'CreateCustomer_DtFundacao'], $(toValidate) ) ) {
                return false;
            }
            $('#CreateCustomer_Individual > .inp_txt > input').each(function() {
                DracoSubmit.Params += 'Individual['+$(this).prop('name')+']='+$(this).val()+'&';
            });
            if( $('input[name=EnTipoCliente]:checked').val() == 'JURIDICA' ) {
                $('#CreateCustomer_Enterprise > .inp_txt > input').each(function() {
                    DracoSubmit.Params += 'Enterprise['+$(this).prop('name')+']='+$(this).val()+'&';
                });
            }
            $('#CreateCustomer_Contact > .inp_txt > input').each(function() {
                DracoSubmit.Params += 'Contact['+$(this).prop('name')+']='+$(this).val()+'&';
            });
            $('#CreateCustomer_Financial > .inp_txt > input[type=text], select').each(function() {
                DracoSubmit.Params += 'Financial['+$(this).prop('name')+']='+$(this).val()+'&';
            });
            DracoSubmit.Params += 'Financial[EnTipoPagamento]='+$('input[name=EnTipoPagamento]:checked').val()+'&';
            DracoSubmit.Params += 'Financial[EnPeriodicidade]='+$('input[name=EnPeriodicidade]:checked').val()+'&';
            DracoSubmit.Params += '&EnTipoCliente='+$('input[name=EnTipoCliente]').val();
            return true;
        }
    },
    'CriarChamadoTelefonico' : {
        'controllerActionSubmit' : 'atendimento/inserir-chamado-telefonico',
        'validate' : function() {
            if( !isValidForm([], $('input[type=text][id*=CreatePhoneCalled_]')) ) {
                return false;
            }
            $($('input[type=text], textarea, select')).each(function() {
                DracoSubmit.Params += 'PhoneCalled['+$(this).prop('name')+']='+$(this).val()+'&';
            });
            if( $('input[type=checkbox]').prop('checked') ) {
                DracoSubmit.Params += 'PhoneCalled[HasCustomer]='+ $('input[type=checkbox]').prop('checked');
            }
            return true;
        }
    },
    'CriarDepartamento' : {
        'controllerActionSubmit' : 'departamento/inserir',
        'validate' : function() {
            if( !isValidForm([], $('input[type=text][id*=CreateDepartament_]')) ) {
                return false;
            }
            DracoSubmit.Params = 'StDepartamento='+$('#CreateDepartament_StDepartamento').val();
            return true;
        }
    },
    'EditarDepartamento' : {
        'controllerActionSubmit' : 'departamento/atualizar',
        'validate' : function() {
            if( !isValidForm([], $('input[type=text][id*=EditDepartament_]')) ) {
                return false;
            }
            DracoSubmit.Params = 'StDepartamento='+$('#EditDepartament_StDepartamento').val() + '&IDDepartamento=' + $('#EditDepartament_IDDepartamento').val();
            return true;
        }
    },
    'CriarSetor' : {
        'controllerActionSubmit' : 'setor/inserir',
        'validate' : function() {
            if( !isValidForm([], $('input[type=text][id*=CreateSector_]')) ) {
                return false;
            }
            DracoSubmit.Params = 'StSetor='+$('#CreateSector_StSetor').val() + '&IDDepartamento=' + $('#CreateSector_IDDepartamento').val();
            return true;
        }
    },
    'EditarSetor' : {
        'controllerActionSubmit' : 'setor/atualizar',
        'validate' : function() {
            if( !isValidForm([], $('input[type=text][id*=EditSector_]')) ) {
                return false;
            }
            DracoSubmit.Params = 'IDSetor='+$('#EditSector_IDSetor').val()+'&StSetor='+$('#EditSector_StSetor').val() + '&IDDepartamento=' + $('#EditSector_IDDepartamento').val();
            return true;
        }
    },
    'ExcluirSetor' : {
        'controllerActionSubmit' : 'setor/delete',
        'toRedirect' : 'setor/listar-setores',
        'validate' : function() {
            var BoReturn = true;
            $('input[type=checkbox]').each(function() {
                if( BoReturn && !$(this).prop('checked') ) {
                    var IDUsuarioTransferido = $(this).prop('name').replace('isDismiss', '');
                    if( empty($('select[id=DeleteSector_IDNewSector'+IDUsuarioTransferido+']')) ) {
                        BoReturn = false;
                    }
                }
            });

            if(!BoReturn) {
                showError({StMessage:'Um ou mais funcionários não tiveram sua situação definida.'})
                return false;
            }

            var ArDismiss = [];
            var ArUsuarioParams = [];

            $('input[type=checkbox]').each(function() {
                if( $(this).prop('checked') ) {
                    ArDismiss.push( $(this).val() );
                } else {
                    var IDUsuario = $(this).prop('name').replace('isDismiss', '');
                    ArUsuarioParams.push( 'Usuario['+IDUsuario+']='+$('select[name=IDNewSector'+IDUsuario+']').val() );
                }
            });

            DracoSubmit.Params = 'IDSetor='+$('input[name=IDSetor]').val();
            if( ArDismiss.length > 0 ) {
                DracoSubmit.Params += '&Dismiss='+ArDismiss.join(', ');
            }
            if( ArUsuarioParams.length > 0 ) {
                DracoSubmit.Params += '&'+ArUsuarioParams.join('&');
            }
            return true;
        }
    },
    'ExcluirDepartamento' : {
        'controllerActionSubmit' : 'departamento/delete-departamento',
        'toRedirect' : 'departamento/listar-departamentos',
        'validate' : function() {
            var BoValid = true;
            $('select[id*=DeleteDepartament_IDNewSector]').each(function() {
                if( empty($(this)) ) {
                    BoValid = false;
                }
            });
            if( !BoValid ) {
                showError({'StMessage':'Erro: Existem setores que não tiveram seus departamento definido.'})
            }

            var params = [];
            $('select[id*=DeleteDepartament_IDNewSector]').each(function() {
                var IDSetor = $(this).prop('id').replace('DeleteDepartament_IDNewSector','');
                params.push(
                    'setor['+params.length+'][IDSetor]='+IDSetor+'&setor['+params.length+'][IDDepartamento]='+$(this).val()
                );
            });

            DracoSubmit.Params = 'IDDepartamento='+$('input[name=IDDepartamento]').val();
            if( params.length > 0 ) {
                DracoSubmit.Params += '&' + params.join('&');
            }
            return BoValid;
        }
    },
    'CriarFuncao' : {
        'controllerActionSubmit' : 'funcao/inserir-funcao',
        'validate' : function() {
            if( !isValidForm([], $('input[type=text][id*=CreatePosition_]')) ) {
                return false;
            }
            DracoSubmit.Params = 'StFuncao='+$('#CreatePosition_StFuncao').val();
            return true;
        }
    },
    'EditarFuncao' : {
        'controllerActionSubmit' : 'funcao/atualizar-funcao',
        'validate' : function() {
            if( !isValidForm([], $('input[type=text][id*=EditPosition_]')) ) {
                return false;
            }
            DracoSubmit.Params = 'StFuncao='+$('#EditPosition_StFuncao').val() + '&IDFuncao=' + $('#EditPosition_IDFuncao').val();
            return true;
        }
    },
    'CriarPerfil' : {
        'controllerActionSubmit' : 'perfil/inserir',
        'validate' : function() {
            if( !isValidForm([], $('input[type=text][id*=CreateProfile_]')) ) {
                return false;
            }
            DracoSubmit.Params = 'StPerfil='+$('#CreateProfile_StPerfil').val() + '&IDFuncao=' + $('#CreateProfile_IDFuncao').val();
            var i = 0;
            $('input[type=checkbox]:checked').each(function() {
                DracoSubmit.Params += '&ArActions['+(i++)+']='+$(this).val();
            });
            return true;
        }
    },
    'EditarPerfil' : {
        'controllerActionSubmit' : 'perfil/atualizar',
        'validate' : function() {
            if( !isValidForm([], $('input[type=text][id*=EditProfile_]')) ) {
                return false;
            }
            DracoSubmit.Params = 'IDFuncao='+$('#EditProfile_IDFuncao').val()+'&IDPerfil='+$('#EditProfile_IDPerfil').val()+'&StPerfil='+$('#EditProfile_StPerfil').val();
            var i = 0;
            $('input[type=checkbox]:checked').each(function() {
                DracoSubmit.Params += '&ArActions['+(i++)+']='+$(this).val();
            });
            return true;
        }
    },
    'BuscarChamado' : {
        'controllerActionSubmit' : false,
        'validate' : function() {
            var wasSearched = false;
            $('input[type=text][id*=CalledSearch_],select,input[name=EnStatus]:checked,input[name=EnTipo]:checked,input[name=BoPrioridade]:checked').each(function() {
                if( !empty($(this)) ) {
                    wasSearched = true;
                }
            });
            if( !wasSearched ) {
                showError({StMessage:'A busca precisa de pelo menos 1 filtro para ser executado.'});
            }
            return wasSearched;
        }
    },
    'BuscarCliente' : {
        'controllerActionSubmit' : false,
        'validate' : function() {
            var wasSearched = false;
            $('input[type=text],input[type=radio]:checked,select').each(function() {
                if( !empty($(this)) ) {
                    wasSearched = true;
                }
            });
            if( !wasSearched ) {
                showError({StMessage:'A busca precisa de pelo menos um parâmetro para ser executada'});
            }
            return wasSearched;
        }
    },
    'CriarMensagem' : {
        'controllerActionSubmit' : 'atendimento/responder',
        'toRedirect' : '',
        'validate' : function() {
            DracoSubmit.CriarMensagem.toRedirect = Configs.Site.params;
            if( empty($('#Called_Answer')) && empty($('#Called_Note')) ) {
                showError({StMessage:'Você não inseriu nenhuma mensagem a este chamado.'});
                return false;
            }
            var TxResposta = exists($('#Called_Answer')) ? $('#Called_Answer').val() : '';
            DracoSubmit.Params = 'TxResposta='+ TxResposta +'&TxObservacao='+$('#Called_Note').val()+'&IDChamado='+$('#Called_IDChamado').val();
            return true;
        }
    },
    'CriarChamadoInterno' : {
        'controllerActionSubmit' : 'atendimento/inserir-chamado-interno',
        'validate' : function() {
            if( !isValidForm([], $('input[type=text], select, textarea')) ) {
                return false;
            }
            if( empty($('input[type=radio]:checked')) ) {
                showError({StMessage:'Expecifique se o chamado a ser criado é prioritário ou não!'})
                return false;
            }
            DracoSubmit.Params = 'IDSetor='+$('#CreateInternalCalled_IDSetor').val()+'&StTitulo='+$('#CreateInternalCalled_StTitulo').val()+'&TxMensagem='+$('#CreateInternalCalled_TxMensagem').val()+'&EnPrioridade='+$('input[type=radio]:checked').val()
            return true;
        }
    },
    'FiltrarDataRelatorioIndividual' : {
        'controllerActionSubmit' : 'atendimento/date-filter/type/individualReport',
        'validate' : function() {
            DracoSubmit.Params = 'Date[Start]='+$('#InpRep_StartDateFilter').val()+'&Date[End]='+$('#InpRep_EndDateFilter').val();
            return true;
        },
        'tSuccess' : function(response) {
            $('#IndRep_Report').html(response);
            BasePackage.Atendimento.relatorioIndividual(true);
        }
    },
    'FiltrarDataRelatorioPessoal' : {
        'controllerActionSubmit' : 'atendimento/date-filter/type/pessoalReport',
        'validate' : function() {
            DracoSubmit.Params = 'Date[Start]='+$('#InpRep_StartDateFilter').val()+'&Date[End]='+$('#InpRep_EndDateFilter').val();
            return true;
        },
        'tSuccess' : function(response) {
            $('#IndRep_Report').html(response);
            BasePackage.Usuario.relatorios(true);
        }
    },
    'FiltrarDataRelatorioSetor' : {
        'controllerActionSubmit' : 'atendimento/date-filter/type/sectorReport',
        'validate' : function() {
            DracoSubmit.Params = 'Date[Start]='+$('#SecRep_StartDateFilter').val()+'&Date[End]='+$('#SecRep_EndDateFilter').val();
            return true;
        },
        'tSuccess' : function(response) {
            $('#SecRep_Report').html(response);
            BasePackage.Atendimento.relatorioPorSetor(true);
        }
    },
    'FiltrarDataRelatorioDepartamento' : {
        'controllerActionSubmit' : 'atendimento/date-filter/type/departamentReport',
        'validate' : function() {
            DracoSubmit.Params = 'Date[Start]='+$('#DepRep_StartDateFilter').val()+'&Date[End]='+$('#DepRep_EndDateFilter').val();
            return true;
        },
        'tSuccess' : function(response) {
            $('#DepRep_Report').html(response);
            BasePackage.Atendimento.relatorioPorDepartamento(true);
        }
    },
    'DeleteFuncao' : {
        'controllerActionSubmit' : 'funcao/deletar-funcao',
        'toRedirect' : 'funcao/listar-funcoes',
        'validate' : function() {
            if( !isValidForm([], $('select[name*=IDFuncao_Perfil]')) ) {
                showError({'StMessage':'Você não destinou todas as Funções ou Usu&aacute;rios'});
                return false;
            }

            var ArParams = [];
            $('select[name*=IDFuncao_Perfil]').each(function() {
                ArParams.push( 'Perfil['+$(this).prop('name').replace('IDFuncao_Perfil','')+']='+$(this).val() );
            });

            DracoSubmit.Params = ArParams.join('&') + '&IDFuncao=' + $('input[name=IDFuncao]').val();
            return true;
        }
    },
    'Estorno' : {
        'controllerActionSubmit' : 'financeiro/executar-estorno',
        'validate' : function() {
            if( !isValidForm([], $('input[type=text]')) ) {
                return false;
            }
            DracoSubmit.Params = 'FoValor='+DracoFuncs.Money.toDouble($('#Reverse_FoValor').val())+'&DtData='+$('#Reverse_DtData').val()+'&IDFinanceiro='+$('#Reverse_IDFinanceiro').val()
            return true;
        }
    },
    'LancarPagamento' : {
        'controllerActionSubmit' : 'financeiro/executar-lancamento',
        'validate' : function() {
            var BoReturn = true;
            var ArParams = [];
            var ArPeriods = [];
            $('.toggle.Up > .periodo').each(function() {
                ArPeriods.push($(this).html());
            });
            $('.toggle.Up').each(function() {
                var IDPaymentToRelease = $(this).prop('rel');
                var IDPayment = $(this).prop('rel').replace('ReleasePayment_Payment', '')
                if( !isValidForm([], $('#'+IDPaymentToRelease+' > div > input') ) ) {
                    BoReturn = false;
                }
                $('#'+IDPaymentToRelease+' > div > input, #'+IDPaymentToRelease+' > div > select').each(function() {
                    var StParameterValue = $(this).prop('class') != 'price' ? $(this).val() : DracoFuncs.Money.toDouble($(this).val());
                    ArParams.push('Payments['+IDPayment+'][' + $(this).prop('name') + ']=' + StParameterValue );
                })
            })
            if( !BoReturn ) {return false;}
            DracoSubmit.Params = 'IDFinanceiro='+$('#ReleasePayment_IDFinanceiro').val() + '&' + ArParams.join('&');
            return confirm('Você tem certeza que deseja confirmar os pagamentos: ' + ArPeriods.join(','));
        }
    },
    'EditarCliente' : {
        'controllerActionSubmit' : 'cliente/atualizar-cliente',
        'validate' : function() {
            if( !isValidForm(['CustomerEdit_ItRamal', 'CustomerEdit_StComplemento'], $('input[type=text]')) ) {
                return false;
            }
            var ArParams = []
            $('#CustomerEdit_Enterprise > .inp_txt > input').each(function() {
                ArParams.push('Enterprise['+$(this).prop('name')+']='+$(this).val());
            });
            $('#CustomerEdit_Individual > .inp_txt > input').each(function() {
                ArParams.push('Individual['+$(this).prop('name')+']='+$(this).val());
            });
            $('#CustomerEdit_General > .inp_txt > input').each(function() {
                ArParams.push('General['+$(this).prop('name')+']='+$(this).val());
            });
             if ($('#CustomerEdit_ItDesconto').val() >= 100){
                return showError({'StMessage':'Desconto n&atilde;o pode ser maior que 100%'});
            }
            DracoSubmit.Params = ArParams.join('&') + '&IDCliente='+$('#CustomerEdit_IDCliente').val();
            return true;
        }
    },
        'DeletePerfil' : {
            'controllerActionSubmit' : 'perfil/deletar-perfil',
            'toRedirect' : 'perfil/listar-perfis',
            'validate' : function() {
                if( !isValidForm([], $('select[name*=IDNewPerfil]')) ) {
                    showError({'StMessage':'Você não destinou todas os Usu&aacute;rios'});
                    return false;
                }

                var ArParams = [];
                $('select[name*=IDNewPerfil]').each(function() {
                    ArParams.push( 'Usuario['+$(this).prop('name').replace('IDNewPerfil','')+']='+$(this).val() );
                });

                DracoSubmit.Params = ArParams.join('&') + '&IDPerfil=' + $('input[name=IDPerfil]').val();
                return true;
            }
        },
        'LancarPagamentoFuncionario' : {
            'controllerActionSubmit' : 'administracao/executar-pagamento',
            'toRedirect' : 'administracao/controle-pagamento',
            'validate' : function() {
                var BoReturn = true;
                var ArParams = [];
                var ArPeriods = []
                $('.toggle.Up > .periodo').each(function() {
                    ArPeriods.push($(this).html())
                });
                $('.toggle.Up').each(function() {
                    var IDPaymentToRelease = $(this).prop('rel');
                    var IDPayment = $(this).prop('rel').replace('ReleasePayment_Payment', '')
                    if( !isValidForm([], $('#'+IDPaymentToRelease+' > div > input') ) ) {
                        BoReturn = false;
                    }
                    $('#'+IDPaymentToRelease+' > div > input').each(function() {
                        var StParameterValue = $(this).prop('class') != 'price' ? $(this).val() : DracoFuncs.Money.toDouble($(this).val());
                        ArParams.push('Payments['+IDPayment+'][' + $(this).prop('name') + ']=' + StParameterValue );
                    })
                })
                if( !BoReturn ) {return false;}
                DracoSubmit.Params = 'IDUsuario='+ $('#ReleasePayment_IDUsuario').val() + '&' + ArParams.join('&');
                return confirm('Você tem certeza que deseja confirmar os pagamentos: ' + ArPeriods.join(','));
            }
        },
        'EditarPlano':{
            'controllerActionSubmit' : 'planos/atualizar-plano',
             'toRedirect' : 'planos/listar-planos',
            'validate' : function(){
                if (!isValidForm([],$('input[id*=PlanEdit]'))){
                    return false;
                }
                if ($('#PlanEdit_ItDesconto').val() >= 100){
                    return showError({'StMessage':'Desconto n&atilde;o pode ser maior que 100%'});
                }
                DracoSubmit.Params = 'StNome='+$('#PlanEdit_StNome').val()+'&ItDesconto='+ $('#PlanEdit_ItDesconto').val()+'&FoPreco='+ DracoFuncs.Money.toDouble($('#PlanEdit_FoPreco').val())+'&TxDescricao='+ $('#PlanEdit_TxDescricao').val()+'&IDPlano='+ $('#PlanEdit_IDPlano').val();
                return true;
            }
        },
        'CadastrarPlano':{
            'controllerActionSubmit' : 'planos/inserir-plano',
            'toRedirect' : 'planos/listar-planos',
            'validate' : function(){
                if(!isValidForm([],$('input[id*=CreatePlans]'))){
                    return false;
                }
                if ($('#CreatePlans_ItDesconto').val() >= 100){
                    return showError({'StMessage':'Desconto n&atilde;o pode ser maior que 100%'});
                }
                DracoSubmit.Params = 'StNome='+$('#CreatePlans_StNome').val()+'&ItDesconto='+ $('#CreatePlans_ItDesconto').val()+'&FoPreco='+ DracoFuncs.Money.toDouble($('#CreatePlans_FoPreco').val())+'&TxDescricao='+ $('#CreatePlans_TxDescricao').val();
                 return true;
            }
        },
        'EditarDadosFinanceiro' : {
            'controllerActionSubmit' : 'financeiro/atualizar-dados-financeiro',
            'toRedirect' : 'financeiro/listar-clientes',
            'validate' : function(){
                if( !isValidForm([], $('input[type=text],select')) ) {
                    return false;
                }
                if( $('#FinancialEdit_ItDesconto').val() > 100 ) {
                    showError( {StMessage: 'O cliente atingiu o máximo de desconto permitido.'} );
                    return false;
                }
                if( empty($('input[type=radio][name=EnPeriodicidade]:checked')) ) {
                    showError( {StMessage: 'O campo "Periodicidade" não está marcado.'} );
                    return false;
                }
                if( empty($('input[type=radio][name=EnTipoPagamento]:checked')) ) {
                    showError( {StMessage: 'O campo "Tipo de Pagamento" não está marcado.'} );
                    return false;
                }
                DracoSubmit.Params += 'IDPlano='+$('#FinancialEdit_IDPlano').val()+'&EnTipoPagamento='+$('input[name=EnTipoPagamento]:checked').val()+'&EnPeriodicidade='+$('input[name=EnPeriodicidade]:checked').val()+'&IDFinanceiro='+$('#FinancialEdit_IDFinanceiro').val()+'&ItDesconto='+$('#FinancialEdit_ItDesconto').val();
                return true;
            }
        },
        'CriarAviso' : {
            'controllerActionSubmit' : 'aviso/inserir',
            'toRedirect' : 'aviso/listar',
            'validate' : function(){
                if( !isValidForm([], $('input[type=text], textarea, select')) ) {
                    return false;
                }
                DracoSubmit.Params = 'StTitulo='+$('#CreateNotice_StTitulo').val()+'&IDCategoria='+$('#CreateNotice_IDCategoria').val()+'&IDSetor='+$('#CreateNotice_IDSetor').val()+'&TxAviso='+$('#CreateNotice_TxAviso').val()+'&DtInicio='+$('#CreateNotice_DtInicio').val()+'&DtDesativar='+$('#CreateNotice_DtDesativar').val();
                return true;
            }
        },
        'EditarAviso' : {
            'controllerActionSubmit' : 'aviso/atualizar',
            'toRedirect' : 'aviso/listar',
            'validate' : function(){
                if( !isValidForm([], $('input[type=text], textarea, select')) ) {
                    return false;
                }
                DracoSubmit.Params = 'IDAviso='+$('#EditNotice_IDAviso').val()+'&StTitulo='+$('#EditNotice_StTitulo').val()+'&IDCategoria='+$('#EditNotice_IDCategoria').val()+'&IDSetor='+$('#EditNotice_IDSetor').val()+'&TxAviso='+$('#EditNotice_TxAviso').val()+'&DtInicio='+$('#EditNotice_DtInicio').val()+'&DtDesativar='+$('#EditNotice_DtDesativar').val();
                return true;
            }
        },
        'CriarAnotacao' : {
            'controllerActionSubmit' : 'anotacao/inserir',
            'toRedirect' : 'ferramenta/listar-anotacoes',
            'validate' : function(){
                if( !isValidForm([], $('input[type=text], textarea')) ) {
                    return false;
                }
                DracoSubmit.Params = 'StTitulo='+$('#CreateNote_StTitulo').val()+'&TxAnotacao='+$('#CreateNote_TxAnotacao').val();
                return true;
            }
        },
        'EditarAnotacao' : {
            'controllerActionSubmit' : 'anotacao/atualizar',
            'toRedirect' : 'ferramenta/listar-anotacoes',
            'validate' : function() {
                if( !isValidForm([], $('input[type=text], textarea')) ) {
                    return false;
                }
                DracoSubmit.Params = 'StTitulo='+$('#EditNote_StTitulo').val()+'&TxAnotacao='+$('#EditNote_TxAnotacao').val()+'&IDAnotacao='+$('#EditNote_IDAnotacao').val();
                return true;
            }
        },
        'CriarPergunta' : {
            'controllerActionSubmit' : 'faq/inserir',
            'toRedirect' : 'faq/listar-perguntas',
            'validate' : function() {
                if( !isValidForm([], $('input[type=text], textarea')) ) {
                    return false;
                }
                DracoSubmit.Params = 'StTitulo='+$('#CreateQuestion_StTitulo').val()+'&TxResposta='+$('#CreateQuestion_TxAnotacao').val();
                return true;
            }
        },
        'EditarPergunta' : {
            'controllerActionSubmit' : 'faq/atualizar',
            'toRedirect' : 'faq/listar-perguntas',
            'validate' : function() {
                if( !isValidForm([], $('input[type=text], textarea')) ) {
                    return false;
                }
                DracoSubmit.Params = 'StTitulo='+$('#EditQuestion_StTitulo').val()+'&TxResposta='+$('#EditQuestion_TxAnotacao').val()+'&IDFaq='+$('#EditQuestion_IDFaq').val();
                return true;
            }
        }
};

var FieldsProperties = {
    'Cpf' : {
        'required' : true,
        'limit' : 14,
        'mask' : '999.999.999-99',
        'placeHolder' : '_'
    },
    'Rg' : {
        'required' : true,
        'limit' : 10,
        'mask' : false,
        'placeHolder' : false
    },
    'Date' : {
        'required' : true,
        'limit' : 10,
        'mask' : '99/99/9999',
        'placeHolder' : '_'
    },
    'ZipCode' : {
        'required' : true,
        'limit' : 9,
        'mask' : '99999-999',
        'placeHolder' : '_'
    },
    'Phone' : {
        'required' : true,
        'limit' : 9,
        'mask' : '9999-9999',
        'placeHolder' : '_'
    },
    'DddPhone' : {
        'required' : true,
        'limit' : 2,
        'mask' : '99',
        'placeHolder' : '_'
    },
    'Uf' : {
        'required' : true,
        'limit' : 2,
        'mask' : 'aa',
        'placeHolder' : '_'
    },
    'Vat' : {
        'required' : true,
        'limit' : '15',
        'mask' : '99.999.999/9999-99',
        'placeHolder' : '_'
    },
    'Percent' : {
        'required' : true,
        'limit' : 3,
        'mask' : '9?99',
        'placeHolder' : '_'
    }
};

var Menu = {
    'start' : function() {
        Menu.clickSubmenu();
        Menu.setCurrentMenu();
        Menu.setSubMenu();
    },
    'clickSubmenu' : function() {
        $("p.menu_head").click(function() {
            $(this).css({backgroundImage:"url(views/dracosys/images/down.png) no-repeat"}).next("div.menu_body").slideToggle(300).siblings("div.menu_body").slideUp("slow");
            $(this).siblings().css({backgroundImage:"url(views/dracosys/images/left.png) no-repeat"});
        });
        $("p.submenu_head").click(function() {
            $(this).css({backgroundImage:"url(views/dracosys/images/down.png) no-repeat"}).next("div.submenu_body").slideToggle(300).siblings("div.submenu_body").slideUp("slow");
            $(this).siblings().css({backgroundImage:"url(views/dracosys/images/left.png) no-repeat"});
        });
    },
    'setCurrentMenu' : function() {
        var StController = Configs.Menu.main != '' ? Configs.Menu.main : 'Home';
        $('#DrMenu'+StController).attr('class','current');
        if( StController != 'Home' ) {
            $('#DrSub'+StController).attr('class', 'show');
        }
    },
    'setSubMenu' : function() {
        $('a[id*=DrMenu]').click(function() {
            var StSufix = $(this).prop('id').replace('DrMenu', '');

            var StCurrentSufix = $('a[id*=DrMenu][class=current]').prop('id').replace('DrMenu', '');
            $('#DrSub'+StCurrentSufix).attr('class', 'hide');
            $('#DrMenu'+StCurrentSufix).removeAttr('class');

            $('#DrSub'+StSufix).attr('class', 'show');
            $('#DrMenu'+StSufix).attr('class', 'current');
        });
    }
};

var DracoFuncs = {
    'ajaxForm' : function(StName) {
        $('form[name='+StName+']').submit(function() {
            var formActionMethod = StName.replace('Form', '');
            DracoSubmit.submit(DracoSubmit[formActionMethod]);
            return false;
        });
    },
    'setProperties' : function() {
        $('input').focus(function(){
            var StType = $(this).prop('class');
            if( FieldsProperties[StType] ) {
                if( FieldsProperties[StType].mask ) {
                    var placeHolder = FieldsProperties[StType].placeHolder ? FieldsProperties[StType].placeHolder : '';
                    $(this).mask(FieldsProperties[StType].mask,{
                        'placeholder':placeHolder
                    });
                } else {
                    $(this).attr('maxlength', FieldsProperties[StType].limit);
                }
            }
        });
    },
    'calendar' : function(IDInput) {
        $('#'+IDInput).focus(function(){
            $(this).calendario({
                target:'#'+IDInput,
                top:40,
                left:0
            });
        });
    },
    'Money' : {
        'priceFormat' : function(){
            $('.price').priceFormat({
                'prefix' : 'R$ ',
                'thousandsSeparator' : '.',
                'centsSeparator' : ','
            });
        },
        'toPrice' : function(value) {
            value = value.toString();
            var cents = value.indexOf('.') > 0 ? value.substr( value.indexOf('.')+1, value.length ) : '00';
            var reais = value.indexOf('.') > 0 ? value.substr(0, value.indexOf('.')) : value ;
            var inversedReais = StringUtils.reverse(reais)
            var decimalCounter = 1;
            reais = '';
            for( var i in inversedReais ) {
                reais += inversedReais[i];
                if( decimalCounter%3 == 0 && decimalCounter != 3 ) {
                    reais += '.';
                    decimalCounter = 0;
                }
                decimalCounter++;
            }
            return 'R$ ' + StringUtils.reverse(reais) + ',' + cents;
        },
        'toDouble' : function( money ) {
            return StringUtils.replaceAll(money, '.', '').replace('R$ ', '').replace(',', '.');
        }
    },
    'PasswordMeter' : {
        'tInputPass' : null,
        'ArLetter' : [],
        'points' : 0,
        'requires' : {
            'letter6' : {
                'points' : 20,
                'complete' : false
            },
            'letter10' : {
                'points' : 10,
                'complete' : false
            },
            'lowercase' : {
                'points' : 15,
                'complete' : false
            },
            'uppercase' : {
                'points' : 15,
                'complete' : false
            },
            'number' : {
                'points' : 15,
                'complete' : false
            },
            'special' : {
                'points' : 25,
                'complete' : false
            }
        },
        'ratings' : {
            'empty' : {
                'label' : 'Vazio',
                'min': 0,
                'max': 0,
                'pass': false
            },
            'weak' : {
                'label' : 'Fraca',
                'min' : 1,
                'max' : 29,
                'pass' : false
            },
            'fair' : {
                'label': 'Regular',
                'min' : 30,
                'max' : 59,
                'pass' : false
            },
            'good' : {
                'label': 'Boa',
                'min' : 60,
                'max' : 85,
                'pass' : true
            },
            'great' : {
                'label': 'Otima',
                'min' : 86,
                'max' : 100,
                'pass' : true
            }
        },
        'init' : function( IDInputPass ) {
            DracoFuncs.PasswordMeter.tInputPass = $('#'+IDInputPass);
            $(DracoFuncs.PasswordMeter.tInputPass).keypress(DracoFuncs.PasswordMeter.getKeyPress);
            $(DracoFuncs.PasswordMeter.tInputPass).keyup(DracoFuncs.PasswordMeter.backspaceAnalyzer); //#Só chama se for 8
        },
        'getKeyPress' : function(e) {
            if( !DracoFuncs.PasswordMeter.getLetter(e) ) {
                return false;
            }
            DracoFuncs.PasswordMeter.passAnalyzer();
            DracoFuncs.PasswordMeter.showResult();
            return true;
        },
        'backspaceAnalyzer' : function(e) {
            if(e.which == 8) {
                DracoFuncs.PasswordMeter.reanalyze();
            }
        },
        'reanalyze' : function() {
            DracoFuncs.PasswordMeter.ArLetter = [];
            DracoFuncs.PasswordMeter.points = 0;
            for( var i in DracoFuncs.PasswordMeter.requires ) {
                DracoFuncs.PasswordMeter.requires[i].complete = false;
            }
            var StConteudo = $('#ChangePass_NewPass').val();
            var len = StConteudo.length;
            for( var j = 0; j < len; j++ ) {
                DracoFuncs.PasswordMeter.ArLetter.push(StConteudo.charCodeAt(j));
            }
            DracoFuncs.PasswordMeter.passAnalyzer();
            DracoFuncs.PasswordMeter.showResult();
        },
        'getLetter' : function(e) {
            if( !isKeys(e.which, [{'min':48,'max':57}, {'min':65,'max':90}, {'min':97,'max':122}, {'min':33,'max':47}, 8, 0]) ) {
                return false;
            }
            if( e.which != 8 ) {
                DracoFuncs.PasswordMeter.ArLetter.push(e.which);
            }
            return true;
        },
        'passAnalyzer' : function() {
            var len = DracoFuncs.PasswordMeter.ArLetter.length;
            if( len >= 6 && !DracoFuncs.PasswordMeter.requires.letter6.complete ) {
                DracoFuncs.PasswordMeter.requires.letter6.complete = true;
                DracoFuncs.PasswordMeter.points += DracoFuncs.PasswordMeter.requires.letter6.points;
            } else if( len >= 10 && !DracoFuncs.PasswordMeter.requires.letter10.complete ) {
                DracoFuncs.PasswordMeter.requires.letter10.complete = true;
                DracoFuncs.PasswordMeter.points += DracoFuncs.PasswordMeter.requires.letter10.points;
            }
            for(var i = 0; i < len; i++) {
                if( DracoFuncs.PasswordMeter.ArLetter[i] >= 48 && DracoFuncs.PasswordMeter.ArLetter[i] <= 57 && !DracoFuncs.PasswordMeter.requires.number.complete ) {
                    DracoFuncs.PasswordMeter.requires.number.complete = true;
                    DracoFuncs.PasswordMeter.points += DracoFuncs.PasswordMeter.requires.number.points;
                } else if( DracoFuncs.PasswordMeter.ArLetter[i] >= 65 && DracoFuncs.PasswordMeter.ArLetter[i] <= 90 && !DracoFuncs.PasswordMeter.requires.uppercase.complete ) {
                    DracoFuncs.PasswordMeter.requires.uppercase.complete = true;
                    DracoFuncs.PasswordMeter.points += DracoFuncs.PasswordMeter.requires.uppercase.points;
                } else if( DracoFuncs.PasswordMeter.ArLetter[i] >= 97 && DracoFuncs.PasswordMeter.ArLetter[i] <= 122 && !DracoFuncs.PasswordMeter.requires.lowercase.complete ) {
                    DracoFuncs.PasswordMeter.requires.lowercase.complete = true;
                    DracoFuncs.PasswordMeter.points += DracoFuncs.PasswordMeter.requires.lowercase.points;
                } else if( DracoFuncs.PasswordMeter.ArLetter[i] >= 33 && DracoFuncs.PasswordMeter.ArLetter[i] <= 47 && !DracoFuncs.PasswordMeter.requires.special.complete ) {
                    DracoFuncs.PasswordMeter.requires.special.complete = true;
                    DracoFuncs.PasswordMeter.points += DracoFuncs.PasswordMeter.requires.special.points;
                }
            }
        },
        'showResult' : function() {
            var StClassificacao = DracoFuncs.PasswordMeter.getLabel();
            $('span#label').text( DracoFuncs.PasswordMeter.points + '% (' + StClassificacao + ')' );
            $('#fullbar > #progress').css('width', DracoFuncs.PasswordMeter.points + '%');
        },
        'getLabel' : function() {
            var StLabel = '';
            for( var i in DracoFuncs.PasswordMeter.ratings ) {
                if( DracoFuncs.PasswordMeter.ratings[i].min <= DracoFuncs.PasswordMeter.points && DracoFuncs.PasswordMeter.ratings[i].max >= DracoFuncs.PasswordMeter.points ) {
                    StLabel = DracoFuncs.PasswordMeter.ratings[i].label;
                }
            }
            return StLabel;
        }
    },
    'ToolTip' : {
        'init' : function(StClassHtmlTooltip, StReplaceRel, css, change) {
            $('*[rel=tooltip]').hover(
                function(e){
                    var StInner = change.over != undefined ? change.over : false;
                    var IDTooltip = $(this).prop('href').replace(location.href, '').replace('#'+StReplaceRel, '');
                    var HtmlTooltip = $('#'+StClassHtmlTooltip+IDTooltip).html();
                    $('body').append('<div class="tooltip">'+HtmlTooltip+'</div>');
                    $('.tooltip').css({
                        top : $(e.currentTarget).offset().top + css.top,
                        left : e.pageX + css.left,
                        width: css.width
                    }).fadeIn();
                    if( change.over ) {
                        $(this).html(StInner);
                    }
                },
                function(e){
                    var StInner = change.out != undefined ? change.out : $(this).html();
                    $('.tooltip').remove();
                    $(this).html(StInner);
                }
            ).mousemove(function(e){
                        $('.tooltip').css({
                            top : $(e.currentTarget).offset().top + css.top,
                            left : e.pageX + css.left
                        }).fadeIn();
            }).click(function() {
                return false;
            });
        }
    },
    'TableList' : {
        'Configure' : {
            'init' : function(Table, sortList, headers, filter) {
                if( !exists($('.nodata')) ) {
                    $(Table).tablesorter({
                        sortList:sortList,
                        headers:headers,
                        widgets: ['zebra']
                    });
                }
                DracoFuncs.TableList.Filter.init(filter);
            }
        },
        'Filter' : {
            'selected' : false,
            'filterType' : '',
            'init' : function(filter) {
                DracoFuncs.TableList.Filter.selected = filter != undefined ? $(filter.selected) : false;
                DracoFuncs.TableList.Filter.filterType = filter != undefined ? filter.type : false;
                $('a[rel=filter]').bind('click', DracoFuncs.TableList.Filter.filterHandler);
            },
            'filterHandler' : function(e) {
                var IdFilter = e.target.href.substr( e.target.href.indexOf('#')+1, e.target.href.length );
                if(IdFilter == $(DracoFuncs.TableList.Filter.selected).prop('id') ) {
                    return false;
                }
                if( DracoFuncs.TableList.Filter.selected ) {
                    $(DracoFuncs.TableList.Filter.selected).attr('class', 'noselected');
                }
                $('#'+IdFilter).attr('class', 'selected');
                DracoFuncs.TableList.Filter.selected = $('#'+IdFilter);
                return false;
            },
            'create' : function(IDTable, filterKey, controller) {
                $('#'+filterKey).bind('click', function() {
                    doRequest('post', Configs.Site.url+controller+'/filter/type/'+DracoFuncs.TableList.Filter.filterType, 'filterkey='+filterKey, function(resposta) {
                        DracoFuncs.TableList.appendBody(resposta, IDTable);
                    });
                    return false;
                });
            }
        },
        'appendBody' : function(StBody, IDTable) {
            $('#'+IDTable+' > tbody').html(StBody);
            $('#'+IDTable).trigger("update");
        }
    },
    'Toggle' : {
        'configure' : function(StPrefix) {
            $('.toggleContainer > a').bind('click', function(e) {
               DracoFuncs.Toggle.init(e.target, StPrefix);
               return false;
            });
        },
        'init' : function(tLink, StPrefix) {
            var StRel = $(tLink).prop('rel');
            StPrefix += '_';
            var StSufix = StRel.replace(StPrefix, '');
            $('section[id='+StPrefix+StSufix+']').slideToggle('slow');
            if($(tLink).prop('class') == 'toggle Up') {
                $(tLink).attr('class', 'toggle Down');
                $('section[id='+StPrefix+StSufix+']').attr('style', 'display:none');
            } else if($(tLink).prop('class') == 'toggle Down') {
                $(tLink).attr('class', 'toggle Up');
                $('section[id='+StPrefix+StSufix+']').attr('style', 'display:block');
            }
            return false;
        },
        'Message' : {
            'StPrefix' : '',
            'hideObject' : '',
            'init' : function(StPrefix, hideObject) {
                DracoFuncs.Toggle.Message.StPrefix = StPrefix
                DracoFuncs.Toggle.Message.hideObject = hideObject ? hideObject : 'p' ;
                DracoFuncs.Toggle.Message.maximize();
                DracoFuncs.Toggle.Message.minimize();
            },
            'maximize' : function() {
                $('.maximize').click(function() {
                    var IDMessage = $(this).prop('rel').replace('Maximize_', '');
                    if( $('article[id='+DracoFuncs.Toggle.Message.StPrefix+IDMessage+'] > ' + DracoFuncs.Toggle.Message.hideObject).css('display') == 'none' ){
                        $('article[id='+DracoFuncs.Toggle.Message.StPrefix+IDMessage+'] > ' + DracoFuncs.Toggle.Message.hideObject).toggle('slow');
                    }
                    return false;
                });
            },
            'minimize' : function() {
                $('.minimize').click(function() {
                    var IDMessage = $(this).prop('rel').replace('Minimize_', '');
                    if( $('article[id='+DracoFuncs.Toggle.Message.StPrefix+IDMessage+'] > ' + DracoFuncs.Toggle.Message.hideObject).css('display') == 'block' || $('article[id='+DracoFuncs.Toggle.Message.StPrefix+IDMessage+'] > ' + DracoFuncs.Toggle.Message.hideObject).css('display') == 'inline' ){
                        $('article[id='+DracoFuncs.Toggle.Message.StPrefix+IDMessage+'] > ' + DracoFuncs.Toggle.Message.hideObject).toggle('slow');
                    }
                    return false;
                });
            }
        }
    },
    'LiberationMessage' : {
            'blockMessage' : function() {
                $('#BlockedMessage_Block').bind('click', function() {
                    var IDMensagem = $('#BlockedMessage_IDMensagem').val();
                    doRequest('post', Configs.Site.url + 'mensagem/bloquear-mensagem', 'IDMensagem='+IDMensagem, function(response) {
                        DracoSubmit.tSuccess(response);
                        redirectIn(Configs.Site.url + 'mensagem/respostas-para-liberar', 1500);
                    });
                });
            },
            'unblockMessage' : function() {
                $('#BlockedMessage_Free').bind('click', function() {
                    var IDMensagem = $('#BlockedMessage_IDMensagem').val();
                    doRequest('post', Configs.Site.url + 'mensagem/desbloquear-mensagem', 'IDMensagem='+IDMensagem+'&TxMensagem='+$('#BlockedMessage_TxMensagem').val()+'&IDChamado='+$('#BlockedMessage_IDChamado').val(), function(response) {
                        DracoSubmit.tSuccess(response);
                        redirectIn(Configs.Site.url + 'mensagem/respostas-para-liberar', 1500);
                    });
                });
            }
    },
    'Dependent' : {
        'id' : '',
        'undoRepository' : '',
        'StPrefix' : '',
        'StContainerPrefix' : '',
        'init' : function(StPrefix) {
            DracoFuncs.Dependent.StPrefix = !StPrefix ? DracoFuncs.Dependent.StPrefix: StPrefix;
            DracoFuncs.Dependent.StContainerPrefix = DracoFuncs.Dependent.StPrefix + '_Dependentes';

            $('a[id*=Dependente_Delete]').unbind('click');
            $('a[id*=Dependente_Delete]').bind('click', DracoFuncs.Dependent.remove);

            $('#Dependente_Insert').unbind('click');
            $('#Dependente_Insert').bind('click', DracoFuncs.Dependent.add);

            $('#Dependente_Undo').unbind('click');
            $('#Dependente_Undo').bind('click', DracoFuncs.Dependent.undo);

            if(StPrefix) {
                DracoFuncs.Dependent.id = $('section[id*=Parentesco]').size();
                DracoFuncs.Dependent.idString = DracoFuncs.Dependent.id + '_' + DracoFuncs.Dependent.id;
                DracoFuncs.Dependent.undoRepository = $('#'+DracoFuncs.Dependent.StContainerPrefix).html();
            }
        },
        'undo' : function(e) {
            $('#'+DracoFuncs.Dependent.StContainerPrefix).html( DracoFuncs.Dependent.undoRepository );
            DracoFuncs.Dependent.init();
            return false;
        },
        'add' : function(e) {
            //##Adiciona um dependente
            DracoFuncs.Dependent.idString = DracoFuncs.Dependent.id + '_' + DracoFuncs.Dependent.id;
            $('#'+DracoFuncs.Dependent.StContainerPrefix).append(
            DracoFuncs.Dependent.getHtmlDependent()
        );
            $('a[id=Dependente_Delete'+DracoFuncs.Dependent.idString+']').bind('click', DracoFuncs.Dependent.remove);
            DracoFuncs.setProperties(); //##Mask
            DracoFuncs.Dependent.id++;
            return false;
        },
        'remove' : function(e) {
            //##Remove um dependente
            var tLink = $(e.target);
            var IDDependente = tLink.prop('id').replace('Dependente_Delete', '');
            $('#Parentesco'+IDDependente).remove();
            return false;
        },
        'getHtmlDependent' : function(id) {
            return '<section id="Parentesco'+DracoFuncs.Dependent.idString+'">'+
                '    <div class="Dependente_title">'+
                '        Novo Dependente &QUOT;<span>Nº '+DracoFuncs.Dependent.id+'</span>&QUOT;'+
                '        <a id="Dependente_Delete'+DracoFuncs.Dependent.idString+'" href="#" class="inserted"><span>Delete</span></a>'+
                '    <div>'+
                '    <div class="out_txt big"><label for="'+DracoFuncs.Dependent.StPrefix+'_StNome'+DracoFuncs.Dependent.idString+'">Nome</label></div>'+
                '    <div class="inp_txt big"><input type="text" value="" id="'+DracoFuncs.Dependent.StPrefix+'_StNome'+DracoFuncs.Dependent.idString+'" name="StNomeDependente'+DracoFuncs.Dependent.idString+'" /></div>'+
                '    <div class="out_txt big"><label for="'+DracoFuncs.Dependent.StPrefix+'_DtNascimento'+DracoFuncs.Dependent.idString+'">Nascimento</label></div>'+
                '    <div class="inp_txt big"><input type="text" value="" id="'+DracoFuncs.Dependent.StPrefix+'_DtNascimento'+DracoFuncs.Dependent.idString+'" name="DtNascimentoDependente'+DracoFuncs.Dependent.idString+'" class="Date" /></div>'+
                '    <div class="out_txt big"><label for="'+DracoFuncs.Dependent.StPrefix+'_StGrauParentesco'+DracoFuncs.Dependent.idString+'">Parentesco</label></div>'+
                '    <div class="inp_txt big"><input type="text" value="" id="'+DracoFuncs.Dependent.StPrefix+'_StGrauParentesco'+DracoFuncs.Dependent.idString+'" name="StGrauParentesco'+DracoFuncs.Dependent.idString+'" /></div>'+
                '</section>';
        }
    },
    'selectCase' : {
        'StPrefix' : '',
        'init' : function(ArKeySelects, StPrefix) {
            DracoFuncs.selectCase.StPrefix = StPrefix;
            for(var StKeySelect in ArKeySelects) {
                DracoFuncs.selectCase.loadSelect(ArKeySelects[StKeySelect]);
            }
        },
        'loadSelect' : function(StKeySelect) {
            switch(StKeySelect) {
                case 'sector' :
                    DracoFuncs.selectCase.loadSectorSelect();
                    break;
                case 'profile' :
                    DracoFuncs.selectCase.loadProfileSelect();
                    break;
            }
        },
        'loadSectorSelect' : function() {
            $('#' + DracoFuncs.selectCase.StPrefix + '_IDDepartamento').bind('change', function(e) {
                var IDUsuario = $('#'+DracoFuncs.selectCase.StPrefix+'_IDUsuario').val() ? $('#'+DracoFuncs.selectCase.StPrefix+'_IDUsuario').val() : '';
                var StData = 'IDDepartamento='+$(e.target).val()+'&IDUsuario='+IDUsuario;
                doRequest('post', Configs.Site.url + 'departamento/select-case-setores', StData, function(response) {
                    DracoFuncs.selectCase.append('IDSetor', response);
                })
            });
        },
        'loadProfileSelect' : function() {
            $('#' + DracoFuncs.selectCase.StPrefix + '_IDFuncao').bind('change', function(e) {
                var IDUsuario = $('#'+DracoFuncs.selectCase.StPrefix+'_IDUsuario').val() ? $('#'+DracoFuncs.selectCase.StPrefix+'_IDUsuario').val() : '';
                var StData = 'IDFuncao='+$(e.target).val()+'&IDUsuario='+IDUsuario;
                doRequest('post', Configs.Site.url + 'funcao/select-case-perfil', StData, function(response) {
                    DracoFuncs.selectCase.append('IDPerfil', response);
                })
            });
        },
        'append' : function(StSufix, response) {
            $('#'+DracoFuncs.selectCase.StPrefix + '_' + StSufix).html(response);
        }
    },
    'CustomerSessionToggle' : {
        'IndividualOrEnterprise' : {
            'init' : function() {
                $('#CreateCustomer_Enterprise').attr('class', 'hide');
                $('input[name=EnTipoCliente]').each(function() {
                    $(this).bind('click', DracoFuncs.CustomerSessionToggle.IndividualOrEnterprise.doToggle);
                });
            },
            'doToggle' : function(e) {
                $('#CreateCustomer_Enterprise').toggle('slow');
            }
        },
        'CustomerIndentifier' : {
            'init' : function() {
                $('input[type=checkbox][name=EnCustomer]').click(
                DracoFuncs.CustomerSessionToggle.CustomerIndentifier.doToggle
            );
            },
            'doToggle' : function() {
                if( $('input[type=checkbox][name=EnCustomer]').prop('checked') ) {
                    $('#CreatePhoneCall_CustomerSearch').removeAttr("disabled");
                } else {
                    $('#CreatePhoneCall_CustomerSearch').attr('disabled', true);
                }
            }
        }
    },
    'Called' : {
        'Priority' : {
            'init' : function() {
                $('#Called_PriorityMark').bind('click', function() {
                    DracoFuncs.Called.Priority.doRequest($(this).prop('checked'));
                });
            },
            'doRequest' : function(isPriority) {
                doRequest('post', Configs.Site.url+'atendimento/prioridade', 'EnPrioridade='+isPriority+'&IDChamado='+$('#Called_IDChamado').val(), DracoFuncs.Called.Priority.changePriority);
            },
            'changePriority' : function(response) {
                var tResponse = eval( '(' + response + ')');
                if( tResponse.Type == 'success' ) {
                    DracoFuncs.Called.Priority.showSuccessMessage()
                } else {
                    DracoFuncs.Called.Priority.showErrorMessage(tResponse.StMessage);
                }
            },
            'showErrorMessage' : function(StMessaga) {
                showError({'StMessage':StMessaga}, false);
            },
            'showSuccessMessage' : function() {
                var StMessage = '';
                if( $('#Called_PriorityMark').prop('checked') ) {
                    $('#Called_PriorityMarkLabel').html('Tirar Prioridade');
                    StMessage = 'Este chamado foi marcado como priorit&aacute;rio com sucesso!';
                } else {
                    $('#Called_PriorityMarkLabel').html('Marcar como Prioridade');
                    StMessage = 'Este chamado foi retirado da lista de prioridades com sucesso!';
                }
                showSuccess({StMessage:StMessage});
                redirectIn(location.href, 1500);
            }
        },
        'Close' : {
            'init' : function() {
                $('#Called_Close').bind('click', function() {
                    DracoFuncs.Called.Close.doRequest($(this).prop('checked'));
                });
            },
            'doRequest' : function() {
                if(confirm('Deseja realmente fechar este chamado?')){
                    doRequest('post', Configs.Site.url+'atendimento/fechar-chamado', 'IDChamado='+$('#Called_IDChamado').val(), DracoFuncs.Called.Close.callback);
                }
            },
            'callback' : function(response) {
                var tResponse = eval( '(' + response + ')');
                if( tResponse.Type == 'success' ) {
                    showSuccess({'StMessage' : tResponse.StMessage});
                    redirectIn(location.href, 1500);
                } else {
                    showError(tResponse);
                }
            }
        },
        'ChangeSector' : {
            'init' : function() {
                $('#Called_ChangeSector').bind('click', DracoFuncs.Called.ChangeSector.submit);
            },
            'submit' : function() {
                var tRequest = DracoFuncs.Called.ChangeSector.getRequest();
                if(tRequest.IDNewSector == tRequest.IDOldSector) {
                    showError({'StMessage':'Selecione um novo Departamento ou Setor para efetuar a troca.'});
                    return false;
                }
                var ArParams = [];
                for(var i in tRequest) {
                    ArParams.push(i + '=' + tRequest[i]);
                }
                var StParams = ArParams.join('&');
                doRequest('POST', Configs.Site.url + 'atendimento/trocar-chamado-setor', StParams, DracoFuncs.Called.ChangeSector.changeSector);
                return false;
            },
            'getRequest' : function() {
                return {
                    'IDChamado' : $('#Called_IDChamado').val(),
                    'IDNewSector' : $('#Called_IDSetor').val(),
                    'IDOldSector' : $('#Called_IDSetorChamado').val()
                }
            },
            'changeSector' : function(response) {
                DracoSubmit.tSuccess(response);
                redirectIn(location.href, 1500);
            }
        },
        'ChangeResponsible' : {
            'init' : function() {
                $('#Called_Responsavel').bind('change', DracoFuncs.Called.ChangeResponsible.submit);
            },
            'submit' : function() {
                if( empty($('#Called_IDUsuario')) ) {
                    showError({'StMessage':'Usuario não Selecionado!'})
                }
                DracoSubmit.Params = 'IDNewUser='+$('#Called_IDUsuario').val()+'&IDOldUser='+$('#Called_IDActualResponsible').val()+'&IDChamado='+$('#Called_IDChamado').val();
                doRequest('POST', Configs.Site.url + 'atendimento/trocar-responsavel-chamado', DracoSubmit.Params, DracoFuncs.Called.ChangeResponsible.changeResponsible);
                return false;
            },
            'changeResponsible' : function(response) {
                DracoSubmit.tSuccess(response);
                redirectIn(location.href, 1500);
            }
        },
        'Faved' : {
            'init' : function() {
                $('#Called_Faved').bind('click', DracoFuncs.Called.Faved.removeAsPreferred);
                $('#Called_NotFaved').bind('click', DracoFuncs.Called.Faved.addAsPreferred);
            },
            'addAsPreferred' : function() {
                $('#Called_NotFaved').toggle();
                $('#Called_Faved').toggle();
                var IDChamado = $('#Called_IDChamado').val();
                doRequest('post', Configs.Site.url+'atendimento/adicionar-aos-favoritos', 'IDChamado='+IDChamado, function(response) {
                    DracoSubmit.tSuccess(response);
                    redirectIn(location.href, 1500);
                });
            },
             'removeAsPreferred' : function() {
                $('#Called_NotFaved').toggle();
                $('#Called_Faved').toggle();
                var IDChamado = $('#Called_IDChamado').val();
                doRequest('post', Configs.Site.url+'atendimento/remover-dos-favoritos', 'IDChamado='+IDChamado, function(response) {
                    DracoSubmit.tSuccess(response);
                    redirectIn(location.href, 1500);
                });
             }
        }
    },
    'Report' : {
        'Zebra' : {
            'init' : function(ArIds) {
                var color = 0;
                for( var id in ArIds ) {
                    $('table#'+ArIds[id] + ' tbody tr').each(function() {
                        $(this).attr('class', ( color++%2 == 0 ? 'color1' : 'color2' ) );
                    });
                    color = 0;
                }
            }
        },
        'Pagination' : {
            'StPrefix' : false,
            'selected' : false,
            'init' : function(StPrefix) {
                DracoFuncs.Report.Pagination.StPrefix = StPrefix;
                DracoFuncs.Report.Pagination.selected = $('.selected');
                $('.pagination > a').bind('click', DracoFuncs.Report.Pagination.pagine);
            },
            'pagine' : function(e) {
                var IDReport = $(e.target).prop('rel');
                if( StringUtils.contains($(e.target).prop('class'), 'nonselected') ) {
                    $(DracoFuncs.Report.Pagination.selected).attr('class', 'nonselected borderRadios');
                    $('#' + DracoFuncs.Report.Pagination.StPrefix + '_' + $(DracoFuncs.Report.Pagination.selected).prop('rel')).attr('class', 'Report hide');

                    $('#' + DracoFuncs.Report.Pagination.StPrefix + '_' + IDReport).attr('class', 'Report');
                    DracoFuncs.Report.Pagination.selected = $(e.target).attr('class', 'selected borderRadios');
                }
                return false;
            }
        }
    },
    'Tabs' : {
        'selected' : false,
        'init' : function() {
            DracoFuncs.Tabs.selected = $('.selected').prop('rel');
            $('.tab > a').bind('click', DracoFuncs.Tabs.change)
        },
        'change' : function(e) {
            var IDTab = $(e.target).prop('rel');
            $('#'+DracoFuncs.Tabs.selected).toggle('fast');
            $('a[rel='+DracoFuncs.Tabs.selected+']').attr('class', '');

            $('#'+IDTab).toggle('slow');;
            $(e.target).attr('class', 'selected');

            DracoFuncs.Tabs.selected = IDTab;
            return false;
        }
    },
    'ReleasePayment' : {
        'IDDiscountPayment' : '',
        'IDLiquidPayment' : '',
        'IDGrossSalary' : '',
        'init' : function(IDLiquidPayment, IDDiscountPayment, IDGrossSalary) {
            DracoFuncs.ReleasePayment.IDLiquidPayment = IDLiquidPayment;
            DracoFuncs.ReleasePayment.IDDiscountPayment = IDDiscountPayment;
            DracoFuncs.ReleasePayment.IDGrossSalary = IDGrossSalary;
            $('input[id*='+IDLiquidPayment+']').bind('blur', DracoFuncs.ReleasePayment.change );
        },
        'change' : function(e) {
            IDPeriod = $(e.target).prop('id').replace(DracoFuncs.ReleasePayment.IDLiquidPayment, '');
            var FoGrossValue = DracoFuncs.Money.toDouble( $('#'+DracoFuncs.ReleasePayment.IDGrossSalary+IDPeriod).text() );
            if( parseFloat(FoGrossValue) < parseFloat( DracoFuncs.Money.toDouble( $(e.target).val() ) ) ) {
                $('#'+DracoFuncs.ReleasePayment.IDDiscountPayment+IDPeriod).val('')
                return showError({StMessage:'O Campo "Salario Liquido" para o Periodo: "'+IDPeriod+'" é maior que o Salário Bruto recebido por este usuario.'});
            }

            var FoDescontValue = FoGrossValue - DracoFuncs.Money.toDouble( $(e.target).val() );
            var FoNonDizimaDescontValue = FoDescontValue.toPrecision( FoDescontValue.toString().indexOf('.') + 2);

            $('#'+DracoFuncs.ReleasePayment.IDDiscountPayment+IDPeriod).val( DracoFuncs.Money.toPrice( FoNonDizimaDescontValue ) );
            hideError();
        }
    },
    'Plans' : {
        'init' : function() {
            $('a[id*=PlanosList_disable]').bind('click', function() {
                var IDPlano = $(this).prop('id').replace('PlanosList_disable', '');
                $(this).toggle('slow');
                doRequest('POST', Configs.Site.url+'planos/desativar-plano', 'IDPlano='+IDPlano, DracoSubmit.tSuccess);
                redirectIn(location.href, 1500);
                return false;
            });

            $('a[id*=PlanosList_enable]').bind('click', function() {
                $(this).toggle('slow');
                var IDPlano = $(this).prop('id').replace('PlanosList_enable', '');
                doRequest('POST', Configs.Site.url+'planos/ativar-plano', 'IDPlano='+IDPlano, DracoSubmit.tSuccess);
                redirectIn(location.href, 1500);
                return false;
            });
        }
    },
    'Export' : {
        'StBaseLink' : '',
        'StKey' : '',
        'tFilter' : null,
        'changeUrl' : function(StKey, tFilter) {
            DracoFuncs.Export.StBaseLink = Configs.Site.url + 'exportar/';
            DracoFuncs.Export.StKey = StKey;
            DracoFuncs.Export.tFilter = tFilter;
            DracoFuncs.Export.pdf();
            DracoFuncs.Export.excel();
        },
        'pdf' : function() {
            var StBaseLink = DracoFuncs.Export.StBaseLink + 'pdf-' + DracoFuncs.Export.StKey;
            if( !StringUtils.empty( DracoFuncs.Export.tFilter.Start ) || !StringUtils.empty( DracoFuncs.Export.tFilter.End ) ) {
                StBaseLink += '/filter/' + JSON.stringify( DracoFuncs.Export.tFilter );
            }
            $('.pdf').attr('href', StBaseLink );
        },
        'excel' : function() {
            var StBaseLink = DracoFuncs.Export.StBaseLink + 'excel-' + DracoFuncs.Export.StKey;
            if( !StringUtils.empty( DracoFuncs.Export.tFilter.Start ) || !StringUtils.empty( DracoFuncs.Export.tFilter.End ) ) {
                StBaseLink += '/filter/' + JSON.stringify( DracoFuncs.Export.tFilter );
            }
            $('.xls').attr('href', StBaseLink );
        }
    }
};

var StringUtils = {
    'empty' : function(string) {
        return string == '';
    },
    'reverse' : function(string) {
        var otherString = '';
        for( var i = string.length-1; i >= 0; i-- ) {
            otherString += string[i];
        }
        return otherString;
    },
    'contains' : function(str, value) {
        return str.indexOf(value) > - 1;
    },
    'replaceAll' : function(string, element, replacement) {
        if( !StringUtils.contains(string, element) ) {
            return string;
        }
        return StringUtils.replaceAll( string.replace(element, replacement), element, replacement);
    },
    'camelCase' : function(string, separator) {
        var split = string.split(separator);
        var camelcase = split[0];
        for(var i = 1, len = split.length; i < len; i++) {
            camelcase += StringUtils.ucwords(split[i]);
        }
        return camelcase;
    },
    'ucwords' : function(word) {
        return word.charAt(0).toUpperCase() + word.substring(1, word.length)
    }
};

var FillForm = {
    withJson: function(tObj) {
        var id = '';
        for(  id in tObj.textFields ) {
            if( !StringUtils.empty(tObj.textFields[id]) ) {
                $('#'+id).attr('value', tObj.textFields[id]);
            }
        }
        for( id in tObj.selects ) {
            if( StringUtils.empty(tObj.selects[id]) ) {
                $('#'+id).attr('value', tObj.selects[id]);
            }
        }
        for( id in tObj.checkboxes ) {
            if( StringUtils.empty(tObj.checkboxes[id]) ) {
                $('#'+id).attr('checked', tObj.checkboxes[id]);
            }
        }
        for( var name in tObj.radioButtons ) {
            if( StringUtils.empty(tObj.radioButtons[name]) ) {
                $('input[name='+name+'][value='+tObj.radioButtons[name]+']').attr('checked', true);
            }
        }
    },
    formToJson : function() {
        var formObject = {
            'textFields' : {},
            'checkboxes' : {},
            'radioButtons' : {},
            'selects' : {}
        };
        $('input:text').each(function() {
            formObject['textFields'][ $(this).prop('id') ] = "";
        });
        $(':checkbox').each(function() {
            formObject['checkboxes'][ $(this).prop('id') ] = "";
        });
        $(':radio').each(function() {
            formObject['radioButtons'][ $(this).prop('name') ] = "";
        });
        $('select').each(function() {
            formObject['selects'][ $(this).prop('id') ] = "";
        });

        console.log( JSON.stringify(formObject) );
    },
    forms : {
        'criarCliente' : {
            'json1' : function() {
                return '{"textFields":{"CreateCustomer_StNome":"","CreateCustomer_DtNascimento":"","CreateCustomer_StCpf":"","CreateCustomer_StRg":"","CreateCustomer_StCargo":"","CreateCustomer_StRazaoSocial":"","CreateCustomer_StNomeFantasia":"","CreateCustomer_DtFundacao":"","CreateCustomer_StCnpj":"","CreateCustomer_StEmail":"","CreateCustomer_StEndereco":"","CreateCustomer_StNumero":"","CreateCustomer_StComplemento":"","CreateCustomer_StBairro":"","CreateCustomer_StCidade":"","CreateCustomer_StEstado":"","CreateCustomer_StCep":"","CreateCustomer_StDddTelefone":"","CreateCustomer_StTelefone":"","CreateCustomer_StDddCelular":"","CreateCustomer_StCelular":"","CreateCustomer_ItDesconto":""},"checkboxes":{},"radioButtons":{"EnTipoCliente":"","EnTipoPagamento":"","EnPeriodicidade":""},"selects":{"CreateCustomer_IDPlano":""}}';
            }
        }
    }
};

var Ajax = {
    'Loader' : {
        'init': function(StUrl) {
            if( Ajax.Loader.isNotPing(StUrl) ) {
                $('body').append('<div class="loader"> <img src="'+Configs.Site.loader+'" /> </div>');
            }
        },
        'end' : function() {
            $('.loader').remove();
        },
        'isNotPing' : function(StUrl) {
            return !(StUrl == Configs.Site.ping || StUrl == Configs.Site.userUpdate);
        }
    }
}

function doRequest(StType, StUrl, StData, tSuccess) {
    Ajax.Loader.init(StUrl);
    $.ajax({
        type:StType,
        url:StUrl,
        data:StData,
        success: function(response) {
            Ajax.Loader.end();
            tSuccess.apply(null, [response]);
        },
        error:function(request, status, errorThrown) {
            Ajax.Loader.end();
            var tReturn = {
                message:'Erro interno de requisi&ccedil;&atilde;o, recarregue ou tente novamente. Codigo do Erro: ' + status
            };
            showError(tReturn);
        }
    });
}

function redirect( StUrl ) {
    window.location.href = StUrl;
}

function redirectIn(StUrl, ItMilleseconds) {
    window.setTimeout(function() {redirect( StUrl );}, ItMilleseconds);
}

function hideError() {
    $('.validate').each(function() {
        $(this).attr('class', $(this).prop('class').replace(' validate', '') )
    });
    $('#Messages > p').attr('class', 'hide');
}

function showError( tError, BoComplete ) {
    StMessage = !BoComplete ? tError.StMessage : tError.toString();
    $('#Messages > p').attr('class', 'Error').html(StMessage).show('slow');
}

function showErrorValidate( tField, StName ) {
    showError({
        StMessage: 'O Campo "'+StName+'" é obrigatório.'
    });
    $(tField).attr('class', $(tField).prop('class') + ' validate' )
    $(tField).focus();
    return false;
}

function showSuccess( tSuccess ) {
    $('#Messages > p').attr('class', 'Success').html(tSuccess.StMessage).show('slow');
}

function showMessage( StMessage ) {
    $('#Messages > p').attr('class', 'Message').html(StMessage).show('slow');
}

function ping() {
    doRequest('GET', Configs.Site.ping, false, function() {
        Ping.session();
    });
}

function update() {
    doRequest('GET', Configs.Site.userUpdate, false, function() {
        Ping.user();
    });
}

function debug( tO ) {
    var str = '';
    for(var i in tO) {
        if( i != 'innerHTML' && i != 'textContent')
            str += i + ' --> ' + tO[i] + "\n";
    }
    alert(str);
}

function isKeys( KeyCode, ArKeys ) {
    for(var i in ArKeys) {
        if( typeof(ArKeys[i]) != 'number' ) {
            if( ArKeys[i].min <= KeyCode && ArKeys[i].max >= KeyCode) {
                return true;
            }
        } else if( ArKeys[i] == KeyCode ) {
            return true
        }
    }
    return false;
}

function isValidForm(ArOptionFields, ArFieldsList) {
    var BoReturn = true;
    ArFieldsList.each(function() {
        if( BoReturn ) {
            if( !inArray($(this).prop('id'), ArOptionFields) && empty($(this))  ) {
                showErrorValidate($(this), $(this).prop('name').substr(2));
                BoReturn = false;
            }
        }
    });
    return BoReturn;
}

function inArray(value, array) {
    if(!array) {return false;}
    for(var i in array) {
        if( array[i] == value ) {
            return true;
        }
    }
    return false;
}

function empty( tObj ) {
    if( !exists(tObj) ) {
        return true;
    }
    return ( $(tObj).val() == undefined || StringUtils.empty($(tObj).val()) )  ? true : false;
}

function exists( tObj ) {
    return $(tObj).size() > 0
}

function initBasePackage() {
    try {
        var method = StringUtils.camelCase(Configs.Action, '-');
        BasePackage[ Configs.Controller ][ method ].call();
    } catch(e) {
        console.warn('BasePackage não possui: ' + Configs.Controller + '.' + method);
    }
}

var Ping = {
    'init' : function() {
        Ping.session();
        Ping.user();
    },
    'session' : function() {
        window.setTimeout("ping()", 300000);
    },
    'user' : function() {
        window.setTimeout("update()", 480000);
    }
}